code

컴파일러 모호한 호출 오류-Func <> 또는 작업이있는 익명 메서드 및 메서드 그룹

codestyles 2020. 8. 18. 07:44
반응형

컴파일러 모호한 호출 오류-Func <> 또는 작업이있는 익명 메서드 및 메서드 그룹


함수를 호출하는 데 익명 메서드 (또는 람다 구문)가 아닌 메서드 그룹 구문을 사용하려는 시나리오가 있습니다.

이 함수에는 두 개의 오버로드가 있습니다. 하나는를, 다른 하나 ActionFunc<string>.

익명 메서드 (또는 람다 구문)를 사용하여 두 개의 오버로드를 행복하게 호출 할 수 있지만 메서드 그룹 구문을 사용하면 모호한 호출 의 컴파일러 오류가 발생 합니다. 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 감사의로이 코드를 컴파일 개선 과부하 후보 .


먼저 Jon의 대답이 맞다고 말하겠습니다. 이것은 사양에서 가장 털이 많은 부분 중 하나이므로 Jon에게 먼저 뛰어 들었습니다.

둘째, 다음 줄을 말씀 드리겠습니다.

메서드 그룹에서 호환되는 대리자 형식으로 의 암시 적 변환이 있습니다.

(강조 추가됨) 깊이 오해의 소지가 있고 불행합니다. 여기서 "호환성"이라는 단어를 제거하는 것에 대해 Mads와 이야기를 나눌 것입니다.

이것이 오해의 소지가 있고 불행한 이유는 섹션 15.2, "호환성 위임"을 요구하는 것처럼 보이기 때문입니다. 15.2 절에서는 메소드와 델리게이트 유형 간의 호환성 관계를 설명 했지만 이는 메소드 그룹과 델리게이트 유형 의 변환 가능성에 대한 질문입니다 .

이제 6.6 섹션을 살펴보고 우리가 얻는 것을 볼 수 있습니다.

과부하 해결을 위해 먼저 어떤 과부하가 적용 가능한 후보 인지 결정해야합니다 . 모든 인수가 암시 적으로 형식 매개 변수 유형으로 변환 될 수있는 경우 후보가 적용 가능합니다. 프로그램의 단순화 된 버전을 고려하십시오.

class Program
{
    delegate void D1();
    delegate string D2();
    static string X() { return null; }
    static void Y(D1 d1) {}
    static void Y(D2 d2) {}
    static void Main()
    {
        Y(X);
    }
}

따라서 한 줄씩 살펴 보겠습니다.

An implicit conversion exists from a method group to a compatible delegate type.

I've already discussed how the word "compatible" is unfortunate here. Moving on. We are wondering when doing overload resolution on Y(X), does method group X convert to D1? Does it convert to D2?

Given a delegate type D and an expression E that is classified as a method group, an implicit conversion exists from E to D if E contains at least one method that is applicable [...] to an argument list constructed by use of the parameter types and modifiers of D, as described in the following.

So far so good. X might contain a method that is applicable with the argument lists of D1 or D2.

The compile-time application of a conversion from a method group E to a delegate type D is described in the following.

This line really doesn't say anything interesting.

Note that the existence of an implicit conversion from E to D does not guarantee that the compile-time application of the conversion will succeed without error.

This line is fascinating. It means that there are implicit conversions which exist, but which are subject to being turned into errors! This is a bizarre rule of C#. To digress a moment, here's an example:

void Q(Expression<Func<string>> f){}
string M(int x) { ... }
...
int y = 123;
Q(()=>M(y++));

An increment operation is illegal in an expression tree. However, the lambda is still convertible to the expression tree type, even though if the conversion is ever used, it is an error! The principle here is that we might want to change the rules of what can go in an expression tree later; changing those rules should not change the type system rules. We want to force you to make your programs unambiguous now, so that when we change the rules for expression trees in the future to make them better, we don't introduce breaking changes in overload resolution.

Anyway, this is another example of this sort of bizarre rule. A conversion can exist for the purposes of overload resolution, but be an error to actually use. Though in fact, that is not exactly the situation we are in here.

Moving on:

A single method M is selected corresponding to a method invocation of the form E(A) [...] The argument list A is a list of expressions, each classified as a variable [...] of the corresponding parameter in the formal-parameter-list of D.

OK. So we do overload resolution on X with respect to D1. The formal parameter list of D1 is empty, so we do overload resolution on X() and joy, we find a method "string X()" that works. Similarly, the formal parameter list of D2 is empty. Again, we find that "string X()" is a method that works here too.

The principle here is that determining method group convertibility requires selecting a method from a method group using overload resolution, and overload resolution does not consider return types.

If the algorithm [...] produces an error, then a compile-time error occurs. Otherwise the algorithm produces a single best method M having the same number of parameters as D and the conversion is considered to exist.

There is only one method in the method group X, so it must be the best. We've successfully proven that a conversion exists from X to D1 and from X to D2.

Now, is this line relevant?

The selected method M must be compatible with the delegate type D, or otherwise, a compile-time error occurs.

Actually, no, not in this program. We never get as far as activating this line. Because, remember, what we're doing here is trying to do overload resolution on Y(X). We have two candidates Y(D1) and Y(D2). Both are applicable. Which is better? Nowhere in the specification do we describe betterness between these two possible conversions.

Now, one could certainly argue that a valid conversion is better than one that produces an error. That would then effectively be saying, in this case, that overload resolution DOES consider return types, which is something we want to avoid. The question then is which principle is better: (1) maintain the invariant that overload resolution does not consider return types, or (2) try to pick a conversion we know will work over one we know will not?

This is a judgment call. With lambdas, we do consider the return type in these sorts of conversions, in section 7.4.3.3:

E is an anonymous function, T1 and T2 are delegate types or expression tree types with identical parameter lists, an inferred return type X exists for E in the context of that parameter list, and one of the following holds:

  • T1 has a return type Y1, and T2 has a return type Y2, and the conversion from X to Y1 is better than the conversion from X to Y2

  • T1 has a return type Y, and T2 is void returning

It is unfortunate that method group conversions and lambda conversions are inconsistent in this respect. However, I can live with it.

Anyway, we have no "betterness" rule to determine which conversion is better, X to D1 or X to D2. Therefore we give an ambiguity error on the resolution of Y(X).


EDIT: I think I've got it.

As zinglon says, it's because there's an implicit conversion from GetString to Action even though the compile-time application would fail. Here's the introduction to section 6.6, with some emphasis (mine):

An implicit conversion (§6.1) exists from a method group (§7.1) to a compatible delegate type. Given a delegate type D and an expression E that is classified as a method group, an implicit conversion exists from E to D if E contains at least one method that is applicable in its normal form (§7.4.3.1) to an argument list constructed by use of the parameter types and modifiers of D, as described in the following.

Now, I was getting confused by the first sentence - which talks about a conversion to a compatible delegate type. Action is not a compatible delegate for any method in the GetString method group, but the GetString() method is applicable in its normal form to an argument list constructed by use of the parameter types and modifiers of D. Note that this doesn't talk about the return type of D. That's why it's getting confused... because it would only check for the delegate compatibility of GetString() when applying the conversion, not checking for its existence.

I think it's instructive to leave overloading out of the equation briefly, and see how this difference between a conversion's existence and its applicability can manifest. Here's a short but complete example:

using System;

class Program
{
    static void ActionMethod(Action action) {}
    static void IntMethod(int x) {}

    static string GetString() { return ""; }

    static void Main(string[] args)
    {
        IntMethod(GetString);
        ActionMethod(GetString);
    }
}

Neither of the method invocation expressions in Main compiles, but the error messages are different. Here's the one for IntMethod(GetString):

Test.cs(12,9): error CS1502: The best overloaded method match for 'Program.IntMethod(int)' has some invalid arguments

In other words, section 7.4.3.1 of the spec can't find any applicable function members.

Now here's the error for ActionMethod(GetString):

Test.cs(13,22): error CS0407: 'string Program.GetString()' has the wrong return type

This time it's worked out the method it wants to call - but it's failed to then perform the required conversion. Unfortunately I can't find out the bit of the spec where that final check is performed - it looks like it might be in 7.5.5.1, but I can't see exactly where.


Old answer removed, except for this bit - because I expect Eric could shed light onto the "why" of this question...

Still looking... in the mean time, if we say "Eric Lippert" three times, do you think we'll get a visit (and thus an answer)?


Using Func<string> and Action<string> (obviously very different to Action and Func<string>) in the ClassWithDelegateMethods removes the ambiguity.

The ambiguity also occurs between Action and Func<int>.

I also get the ambiguity error with this:

class Program
{ 
    static void Main(string[] args) 
    { 
        ClassWithSimpleMethods classWithSimpleMethods = new ClassWithSimpleMethods(); 
        ClassWithDelegateMethods classWithDelegateMethods = new ClassWithDelegateMethods(); 

        classWithDelegateMethods.Method(classWithSimpleMethods.GetOne);
    } 
} 

class ClassWithDelegateMethods 
{ 
    public void Method(Func<int> func) { /* do something */ }
    public void Method(Func<string> func) { /* do something */ } 
}

class ClassWithSimpleMethods 
{ 
    public string GetString() { return ""; } 
    public int GetOne() { return 1; }
} 

Further experimentation shows that when passing in a method group by its self, the return type is completely ignored when determining which overload to use.

class Program
{
    static void Main(string[] args)
    {
        ClassWithSimpleMethods classWithSimpleMethods = new ClassWithSimpleMethods();
        ClassWithDelegateMethods classWithDelegateMethods = new ClassWithDelegateMethods();

        //The call is ambiguous between the following methods or properties: 
        //'test.ClassWithDelegateMethods.Method(System.Func<int,int>)' 
        //and 'test.ClassWithDelegateMethods.Method(test.ClassWithDelegateMethods.aDelegate)'
        classWithDelegateMethods.Method(classWithSimpleMethods.GetX);
    }
}

class ClassWithDelegateMethods
{
    public delegate string aDelegate(int x);
    public void Method(Func<int> func) { /* do something */ }
    public void Method(Func<string> func) { /* do something */ }
    public void Method(Func<int, int> func) { /* do something */ }
    public void Method(Func<string, string> func) { /* do something */ }
    public void Method(aDelegate ad) { }
}

class ClassWithSimpleMethods
{
    public string GetString() { return ""; }
    public int GetOne() { return 1; }
    public string GetX(int x) { return x.ToString(); }
} 

The overloading with Func and Action is akin (because both of them are delegates) to

string Function() // Func<string>
{
}

void Function() // Action
{
}

If you notice, the compiler does not know which one to call because they only differ by return types.

참고URL : https://stackoverflow.com/questions/2057146/compiler-ambiguous-invocation-error-anonymous-method-and-method-group-with-fun

반응형