相关疑难解决方法(0)

编译器模糊调用错误 - 具有Func <>或Action的匿名方法和方法组

我有一个场景,我想使用方法组语法而不是匿名方法(或lambda语法)来调用函数.

该函数有两个重载,一个需要一个Action,另一个需要一个Func<string>.

我可以愉快地使用匿名方法(或lambda语法)调用两个重载,但如果我使用方法组语法,则会获得Ambiguous调用的编译器错误.我可以明确的解决方法铸造到ActionFunc<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 …
Run Code Online (Sandbox Code Playgroud)

c# delegates

101
推荐指数
2
解决办法
2万
查看次数

标签 统计

c# ×1

delegates ×1