简体   繁体   中英

C# - overloaded extension methods

In a pretty basic studying exercise I was using LinkedList and when needed to return the last element I mistakingly used the method Last() instead of the property Last and then I started to wonder.

This method is an extension method of IEnumerable, so if it's not overloaded (Visual Studio + Resharper are displaying me the basic IEnumerable extension method signature for this method), It would be very inefficient.

The LinkedList MSDN page specifies most of the extension methods as "Overloaded." but I'm not sure what it means(clicking a method link displays the basic method's explanation) and why doesn't Visual Studio + Resharper show it to me.

Thanks.

An easy mistake to make is to confuse over loading with over riding . When the MSDN page is saying that the methods are overloaded, it means that there are multiple versions of the methods with different parameters.

You cannot override extension methods since they are static.

You cannot technically "override" extension methods, because they are static. However, if a method on your class or interface has the same signature as an extension method, the compiler will prefer the class or interface method over the extension method. So normally the following line:

list.LastOrDefault()

... would actually be compiled as:

Enumerable.LastOrDefault(list);

But in the following code:

public class LinkedList2<T> : LinkedList<T>{
    public T LastOrDefault() {
        return Last.Value;
    }
}
...
var list = new LinkedList2<int>();
list.LastOrDefault();

The compiler is actually going to call LinkedList2.LastOrDefault() instead of Enumerable.LastOrDefault<T>(this IEnumerable<T>) .

Because LinkedList does not have a Last() or LastOrDefault() method, however, you would end up calling the highly-inefficient Enumerable.Last()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM