Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
235 views
in Technique[技术] by (71.8m points)

c# - Extension method priority

I read from https://msdn.microsoft.com/en-us/library/vstudio/bb383977.aspx that extension methods with same name and signature as existing ones on the base type are never called, but what about "overriding" an extension-method itself:

using System;
using System.Linq;
using System.Collections.Generic;


namespace ConsoleApplication1
{

    public class Program
    {

        public static void Main(string[] args)
        {

            var query = (new[] { "Hans", "Birgit" }).Where(x => x == "Hans");
            foreach (var o in query) Console.WriteLine(o);
        }

    }


    public static class MyClass
    {
        public static IEnumerable<T> Where<T>(this IEnumerable<T> source, Func<T, bool> predicate)
        {
            foreach (var obj in source)
                if (predicate(obj)) yield return obj;
        }
    };

}

When I debug this program I DO run into my own extension-method rather then that one provided by System.Linq (although the namespace is included). Did I miss anything or is there also a priority for extension-methods?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...