我有一个场景,我想使用方法组语法而不是匿名方法(或 lambda 语法)来调用函数。
该函数有两个重载,一个接受 Action
,另一个接受 Func<string>
。
我可以愉快地使用匿名方法(或 lambda 语法)调用这两个重载,但是如果使用方法组语法,就会得到 模棱两可的祈祷的编译器错误。我可以通过显式转换为 Action
或 Func<string>
来解决这个问题,但是不认为这是必要的。
有人能解释一下为什么需要显式强制类型转换吗。
下面的代码示例。
class Program
{
static void Main(string[] args)
{
ClassWithSimpleMethods classWithSimpleMethods = new ClassWithSimpleMethods();
ClassWithDelegateMethods classWithDelegateMethods = new ClassWithDelegateMethods();
// These both compile (lambda syntax)
classWithDelegateMethods.Method(() => classWithSimpleMethods.GetString());
classWithDelegateMethods.Method(() => classWithSimpleMethods.DoNothing());
// These also compile (method group with explicit cast)
classWithDelegateMethods.Method((Func<string>)classWithSimpleMethods.GetString);
classWithDelegateMethods.Method((Action)classWithSimpleMethods.DoNothing);
// These both error with "Ambiguous invocation" (method group)
classWithDelegateMethods.Method(classWithSimpleMethods.GetString);
classWithDelegateMethods.Method(classWithSimpleMethods.DoNothing);
}
}
class ClassWithDelegateMethods
{
public void Method(Func<string> func) { /* do something */ }
public void Method(Action action) { /* do something */ }
}
class ClassWithSimpleMethods
{
public string GetString() { return ""; }
public void DoNothing() { }
}
根据 是的在2019年3月20日的评论(我发布这个问题已经9年了!)由于 改进的过载候选人,这段代码编译成 C # 7.3。