开发者

How does C# resolve extension methods call? [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incompl开发者_JS百科ete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center. Closed 11 years ago.

The part of my question is answered in this answer.

However, there is another situation:

public class A { }

public static class ExtendedA
{
    public static void Ext(this A a) { }
}

public static class ExtendedB
{
    public static void Ext(this A a) { }
}

public static class App
{
    public static void Main()
    {
        A a = new A();
        a.Ext();
    }
}

How does the C# compiler chooses the method to call?


If you try to compile all that code in the same namespace, you will get a compiler error on a.Ext(), saying that Ext is an ambiguous function call that cannot be resolved. In order to fix this error, you'll either have to move the extension classes into different namespaces and import only one of them, or invoke the method as a regular static one.

Worded as a direct answer to your question: The C# compiler doesn't choose. It forces you to.


It doesn't -- if the call is completely ambiguous, you get compiler error CS0121:

The call is ambiguous between the following methods or properties: 'ExtendedA.Ext(A)' and 'ExtendedB.Ext(A)'


If you try your own code, it gives following error:

Error 1 The call is ambiguous between the following methods or properties: 'ConsoleApplication3.ExtendedA.Ext(ConsoleApplication3.A)' and 'ConsoleApplication3.ExtendedB.Ext(ConsoleApplication3.A)' c:\temp\trash\ConsoleApplication3\ConsoleApplication3\Program.cs 28 4 ConsoleApplication3

So clearly the compiler tried to resolve the right call like it would have done for overloads but at the end gave up because two methods caused ambiguity.

so, it seems it tries to resolve just like it does for overloaded methods.


You can't add 2 extension functions with the same signature as this will lead to an ambiguity error as the compiler can't distinguish which one to use.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜