真正奇怪的是,您在接口中为可选参数设置的值实际上有所不同。我想您必须质疑该值是接口细节还是实现细节。我会说后者,但事情的表现就像前者。例如,以下代码输出 1 0 2 5 3 7。
// 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);
}
}
}
有趣的是,如果您的接口使参数可选,则实现它的类不必这样做:
// 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);
}
}
}
然而,似乎错误的是,如果您明确地实现接口,那么您在类中为可选值提供的值是没有意义的。在以下示例中,您如何使用值 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);
}
}
}
Eric Lippert 就这个确切的主题写了一个有趣的系列:可选参数极端案例