在接口方法中,您可以声明可选参数,但实现类不必将参数声明为可选参数,就像Eric Lippert解释的那样。另外,在实现类中将参数声明为可选参数,但是在接口中则不能。
那么,在接口中声明可选参数是否有任何原因?如果没有,为什么允许这样做?
示例:
public interface IService1
{
void MyMethod(string text, bool flag = false);
}
public class MyService1a : IService1
{
public void MyMethod(string text, bool flag) {}
}
public class MyService1b : IService1
{
public void MyMethod(string text, bool flag = true) { }
}
public interface IService2
{
void MyMethod(string text, bool flag);
}
public class MyService2b : IService2
{
public void MyMethod(string text, bool flag = false) { }
}