编译器模糊调用错误-使用Func<>或Action的匿名方法和方法组在我的场景中,我希望使用方法组语法而不是匿名方法(或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() { }}C#7.3更新按0 xcde下面的评论是在2019年3月20日(我发布这个问题九年后),这段代码在C#7.3中编译,这要归功于改进的过载候选.
3 回答
- 3 回答
- 0 关注
- 500 浏览
添加回答
举报
0/150
提交
取消