Jam*_*Ide 21 c# optional-parameters c#-4.0
您可以在接口方法中声明可选参数,但不需要实现类来将参数声明为可选参数,正如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) { }
}
Run Code Online (Sandbox Code Playgroud)
Kir*_*huk 22
例:
public interface IService1
{
void MyMethod(string text, bool flag = true);
}
public class MyService1a : IService1
{
public void MyMethod(string text, bool flag) { }
}
Run Code Online (Sandbox Code Playgroud)
用法:
IService1 ser = new MyService1a();
ser.MyMethod("A");
Run Code Online (Sandbox Code Playgroud)
传递给的第二个参数MyService1a将是true接口中的默认参数.
Jon*_*eet 20
这样做的原因是为了让调用者在编译时类型只是接口时更容易使用:
public void Foo(IService1 service)
{
service.MyMethod("Text"); // Calls MyMethod("Text", false)
}
Run Code Online (Sandbox Code Playgroud)
调用者只知道实现的接口而不是具体的类型是相当普遍的 - 所以如果你认为可选参数是一个好主意(它是有争议的),那么在接口上将它们与具体类型一样有意义.