실제로 이상한 점은 인터페이스의 선택적 매개 변수에 입력 한 값이 실제로 달라진다는 것입니다. 값이 인터페이스 세부 사항인지 구현 세부 사항인지 여부를 질문해야한다고 생각합니다. 나는 후자를 말했을 것이지만 물건은 전처럼 행동한다. 다음 코드는 예를 들어 1 0 2 5 3 7을 출력합니다.
실수 것 같다 무엇
// Optput:
// 2 5
namespace ScrapCSConsole
{
using System;
interface IMyTest
{
void MyTestMethod(int notOptional, int optional = 5);
}
class MyTest : IMyTest
{
public void MyTestMethod(int notOptional, int optional)
{
Console.WriteLine(string.Format("{0} {1}", notOptional, optional));
}
}
class Program
{
static void Main(string[] args)
{
MyTest myTest1 = new MyTest();
// The following line won't compile as it does not pass a required
// parameter.
//myTest1.MyTestMethod(1);
IMyTest myTest2 = myTest1;
myTest2.MyTestMethod(2);
}
}
}
그러나 경우이다 : 재미의 종류 무엇
// Output:
// 1 0
// 2 5
// 3 7
namespace ScrapCSConsole
{
using System;
interface IMyTest
{
void MyTestMethod(int notOptional, int optional = 5);
}
interface IMyOtherTest
{
void MyTestMethod(int notOptional, int optional = 7);
}
class MyTest : IMyTest, IMyOtherTest
{
public void MyTestMethod(int notOptional, int optional = 0)
{
Console.WriteLine(string.Format("{0} {1}", notOptional, optional));
}
}
class Program
{
static void Main(string[] args)
{
MyTest myTest1 = new MyTest();
myTest1.MyTestMethod(1);
IMyTest myTest2 = myTest1;
myTest2.MyTestMethod(2);
IMyOtherTest myTest3 = myTest1;
myTest3.MyTestMethod(3);
}
}
}
는 인터페이스를 구현하는 매개 변수 옵션 클래스를 만드는 경우는 동일한 작업을 수행 할 필요가 없다는 것입니다 인터페이스를 명시 적으로 구현하면 클래스에서 옵션 값에 대해 제공하는 값이 무의미합니다. 다음 예제에서 값 9를 어떻게 사용할 수 있습니까? 이것은 컴파일 할 때 경고조차하지 않습니다.
// Optput:
// 2 5
namespace ScrapCSConsole
{
using System;
interface IMyTest
{
void MyTestMethod(int notOptional, int optional = 5);
}
class MyTest : IMyTest
{
void IMyTest.MyTestMethod(int notOptional, int optional = 9)
{
Console.WriteLine(string.Format("{0} {1}", notOptional, optional));
}
}
class Program
{
static void Main(string[] args)
{
MyTest myTest1 = new MyTest();
// The following line won't compile as MyTest method is not available
// without first casting to IMyTest
//myTest1.MyTestMethod(1);
IMyTest myTest2 = new MyTest();
myTest2.MyTestMethod(2);
}
}
}
아래의 Martin의 의견은 다양한 함정에 대한 자세한 예제를 제공하며 컴파일러가 일치하지 않는 기본 인수를 플래그로 표시하기를 바랍니다. 즉, 다른 개발자가 볼 수있는 인터페이스와 구현 수준 모두에서 개발자로서의 의도를 나타 내기 때문에이 코드를 내 코드에서 사용하고 있습니다. –
흥미로운 관련 질문 인 "[인터페이스에서 선택적 매개 변수를 선언 할 이유가 있습니까?] (https : // stackoverflow."[클래스를 구현할 때 인터페이스에 적용되지 않는 C# 4 선택적 매개 변수는 왜 정의되어 있습니까?] (https://stackoverflow.com/questions/4922714/)", 두 번째로 흥미로운 [Lippert의 대답] (https://stackoverflow.com/a/4923642/1028230) – ruffin