private void StringAction(string aString) // method to be called
{
return;
}
private void TestDelegateStatement1() // doesn't work
{
var stringAction = new System.Action(StringAction("a string"));
// Error: "Method expected"
}
private void TestDelegateStatement2() // doesn't work
{
var stringAction = new System.Action(param => StringAction("a string"));
// Error: "System.Argument doesn't take 1 arguments"
stringAction();
}
private void TestDelegateStatement3() // this is ok
{
var stringAction = new System.Action(StringActionCaller);
stringAction();
}
private void StringActionCaller()
{
StringAction("a string");
}
我不明白为什么TestDelegateStatement3
可以工作,但TestDelegateStatement1
失败了。在两种情况下,都提供了一个不带参数的方法给Action
。它们可以调用一个带一个参数(aString
)的方法,但那应该是无关紧要的。它们不需要参数。这是使用lambda表达式不可能完成的,还是我做错了什么?
System.Action stringAction = () => StringAction("a string");
(编译器没有足够的信息来知道var
是一个System.Action
)。 - devuxer