고려 다음과 같은 콘솔 응용 프로그램 :이 프로그램의 출력은 C# 4.0의 기본 매개 변수
class Program
{
static void Main()
{
MyInterface test = new MyClass();
test.MyMethod();
Console.ReadKey();
}
}
interface MyInterface
{
void MyMethod(string myString = "I am the default value on the interface");
}
class MyClass : MyInterface
{
public void MyMethod(string myString = "I am the default value set on the implementing class")
{
Console.WriteLine(myString);
}
}
입니다
:I am the default value on the interface
(1) 당사 매개 변수로를 지정하는 방법이 아니다 값을 제공하지 않고 인터페이스에서 선택 사항. 기본값을 구현 세부 사항으로 간주합니다. 이 코드를 사전 옵션 매개 변수 스타일로 작성하면 인터페이스에 두 개의 오버로드를 만들고 기본값은 구현 클래스에 지정됩니다. 나는. 우리는 할 것이다 :
우리가 기대하는 것처럼 출력interface MyInterface
{
void MyMethod();
void MyMethod(string myString);
}
class MyClass : MyInterface
{
public void MyMethod()
{
MyMethod("I am the default value set on the implementing class");
}
public void MyMethod(string myString)
{
Console.WriteLine(myString);
}
}
,
I am the default value set on the implementing class
(2) 왜 우리는 구현 클래스의 기본 값을 재정의 할 수 없습니다!
부유 한 건배, 나는 문제를 본다. 인터페이스에 값을 제공하지 않고 "선택적"키워드를 추가하는 것이 더 합리적이지 않습니까? 인터페이스에 기본값을 두어야한다는 것은 나에게 의미가 없습니다. – magritte