When the compiler searches for extension methods, it starts with those declared in classes in the same namespace as the calling code, then works outwards until it reaches the global namespace. So if your code is in namespace Foo.Bar.Baz
, it will first search Foo.Bar.Baz
, then Foo.Bar
, then Foo
, then the global namespace. It will stop as soon as it finds any eligible extension methods. If it finds multiple eligible extension methods in the same step, and none is "better" than the other (using normal overloading rules) then you'll get a compile-time error for ambiguity.
Then (if it hasn't found anything) it considers extension methods imported by using
directives. So, if you move your extension method to a different namespace which is unrelated to yours, you'll either get a compile-time error due to ambiguity (if you imported the namespace with a using
directive) or it will only find the System.Linq
method (if you didn't import the namespace containing your method).
This is specified in section 7.6.5.2 of the C# specification.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…