編譯器模糊調(diào)用錯(cuò)誤-使用Func<>或Action的匿名方法和方法組在我的場(chǎng)景中,我希望使用方法組語(yǔ)法而不是匿名方法(或lambda語(yǔ)法)來調(diào)用函數(shù)。該函數(shù)有兩個(gè)重載,一個(gè)采用Action,另一個(gè)Func<string>.我可以很高興地使用匿名方法(或lambda語(yǔ)法)調(diào)用這兩個(gè)重載,但是得到一個(gè)編譯器錯(cuò)誤模糊調(diào)用如果我使用方法組語(yǔ)法。我可以通過顯式轉(zhuǎn)換Action或Func<string>,但不要認(rèn)為這是必要的。誰能解釋為什么需要顯式轉(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下面的評(píng)論是在2019年3月20日(我發(fā)布這個(gè)問題九年后),這段代碼在C#7.3中編譯,這要?dú)w功于改進(jìn)的過載候選.
編譯器模糊調(diào)用錯(cuò)誤-使用Func<>或Action的匿名方法和方法組
翻翻過去那場(chǎng)雪
2019-08-02 07:02:22