Consider the following console application:
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)为什么我们不能在实现类中重写默认值!