开发者

invoking a static method with an instance of the class. why?

开发者 https://www.devze.com 2023-02-20 11:20 出处:网络
This is a small snippet of code that I found. when we make a call object.Max(s=>s.Length) why do we need a st开发者_如何学运维atic method?

This is a small snippet of code that I found. when we make a call

    object.Max(s=>s.Length)

why do we need a st开发者_如何学运维atic method?

    public static TResult Max<TSource, TResult>(
        this IEnumerable<TSource> source,
        Func<TSource, TResult> selector)
    {
        return source.Select(selector).Max();
    }

please update the question title. I couldnot abstract it well.


That is an extension method (via the this modifier on the first parameter). The obj. is passed in as the first argument instead. So:

obj.Max()

is identical to:

DeclaringType.Max(obj, s=>s.Length)

But note that genuine instance methods always take precedence during static analysis, so if the object had a suitable Max method itself, it would be chosen instead of the extension method.

Extension methods must be static methods on non-nested static classes.

0

精彩评论

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