代理上的可选参数无法正常工作
为什么这段代码不能编译?
delegate int xxx(bool x = true); xxx test = f; int f() { return 4; }
可选参数用于主叫方 – 而不是有效的单方法接口实现 。 所以例如,这应该编译:
delegate void SimpleDelegate(bool x = true); static void Main() { SimpleDelegate x = Foo; x(); // Will print "True" } static void Foo(bool y) { Console.WriteLine(y); }
会发生什么test(false)
? 它会破坏堆栈,因为签名必须匹配。
试试这种方式:
static int f(bool a) { return 4; }
因为可选参数不会更改方法的基础签名,这对委托很重要。
您的代码期望的是可选参数,如果您不使用它,则不在方法签名中 – 这是不正确的。