Joh*_*pin 5 c# interface optional-parameters
我一直在玩可选参数,并且遇到了以下情况.
如果我的类上有一个方法,其中所有参数都是可选的,我可以编写以下代码:
public class Test
{
public int A(int foo = 7, int bar = 6)
{
return foo*bar;
}
}
public class TestRunner
{
public void B()
{
Test test = new Test();
Console.WriteLine(test.A()); // this recognises I can call A() with no parameters
}
}
Run Code Online (Sandbox Code Playgroud)
如果我然后创建一个接口,如:
public interface IAInterface
{
int A();
}
Run Code Online (Sandbox Code Playgroud)
如果我使Test类实现此接口,那么它将无法编译,因为它表示来自IAInterface的接口成员A()未实现.为什么接口实现没有被解析为具有所有可选参数的方法?
这是两种不同的方法。一个有两个参数,一个有零。可选参数只是语法糖。您的方法B将被编译为以下内容:
public void B()
{
Test test = new Test();
Console.WriteLine(test.A(7, 6));
}
Run Code Online (Sandbox Code Playgroud)
您可以通过查看生成的 IL 代码来验证这一点。