編譯器模糊調(diào)用錯誤-使用Func<>或Action的匿名方法和方法組在我的場景中,我希望使用方法組語法而不是匿名方法(或lambda語法)來調(diào)用函數(shù)。該函數(shù)有兩個重載,一個采用Action,另一個Func<string>.我可以很高興地使用匿名方法(或lambda語法)調(diào)用這兩個重載,但是得到一個編譯器錯誤模糊調(diào)用如果我使用方法組語法。我可以通過顯式轉(zhuǎn)換Action或Func<string>,但不要認為這是必要的。誰能解釋為什么需要顯式轉(zhuǎn)換。下面的代碼示例。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日(我發(fā)布這個問題九年后),這段代碼在C#7.3中編譯,這要歸功于改進的過載候選.
- 3 回答
- 0 關(guān)注
- 297 瀏覽
添加回答
舉報
0/150
提交
取消