【发布时间】:2011-08-03 22:05:20
【问题描述】:
为什么这段代码不能编译?
delegate int xxx(bool x = true);
xxx test = f;
int f()
{
return 4;
}
【问题讨论】:
标签: c# delegates optional-parameters
为什么这段代码不能编译?
delegate int xxx(bool x = true);
xxx test = f;
int f()
{
return 4;
}
【问题讨论】:
标签: c# delegates optional-parameters
可选参数用于调用端 - 而不是像单方法接口实现那样有效。例如,这个应该编译:
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;
}
【讨论】:
因为可选参数不会改变方法的底层签名,这对委托很重要。
如果您不使用它,您的代码所期望的是不在方法签名中的可选参数 - 这是不正确的。
【讨论】: