【发布时间】:2011-12-28 19:38:48
【问题描述】:
考虑以下控制台应用程序:
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) 为什么没有办法在接口上将参数指定为可选而不提供值。我认为默认值是实现细节。如果我们以预选参数样式编写此代码,我们将在接口中创建两个重载,并在实现类中指定默认值。 IE。我们会:
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) 为什么我们不能覆盖实现类中的默认值!
【问题讨论】: