How does C# resolve extension methods call? [closed]
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.
精彩评论