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.
精彩评论