質問

Why is the following call ambiguous:

public class Foo
{
    public void Bar<T> (Action<T> simple);
    public void Bar<T1, T2> (Action<T1, T2> complex);
}

...

public class Test
{
    public static void MyComplex (string a, string b) { ... }
}

...

foo.Bar(Test.MyComplex);

Shouldn't it be clear to the compiler to call the Bar<T1,T2>() method?

役に立ちましたか?

解決

If you remove this method public void Bar<T> (Action<T> simple);, your code just will not compile, because you get this exception:

The type arguments for method 'Foo.Bar(System.Action)' cannot be inferred from the usage. Try specifying the type arguments explicitly.

Unfortunately the compiler can not get types from this method, and you should write this code to call method:

new Foo().Bar(new Action<string, string>(Test.MyComplex));

他のヒント

The compiler is trying to infer the generic parameter types for Bar but to do that it needs to know all the argument types. The argument you have (Test.MyComplex) is actually method group, not a delegate so the compiler is also required to insert a conversion to a compatible delegate type. However it can't because it does not know the what delegate types to use because type inference on the method it needs to be compatible with has not completed yet. There's a chicken-and-egg problem and the compiler gives up saying the call is ambiguous. Eric Lippert points out in the comments to a very similar question that in simple cases like this, it could be worked out but at the expense of complicating the overload resolution rules.

Unfortunately you are required to do something that gives the compiler more information:

foo.Bar<string, string>(Test.MyComplex);

or

Action<string, string> action = Test.MyComplex;
foo.Bar(action);
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top