我有一个场景,想要使用方法组语法来调用一个函数,而非使用匿名方法(或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 更新
根据0xcde在2019年3月20日下方的评论(我发表这个问题九年后!),由于改进的重载选择机制,此代码现在可以编译通过 C# 7.3。
<LangVersion>7.3</LangVersion>
)或更高版本,您的示例代码将编译通过,这要归功于改进的重载候选项。 - 0xced