LINQ中的扩展方法

LINQ中的where(),OderByDescending().Select()并不是IEnumerable<T>的方法,却能使用这些方法,查阅了资料发现是用到了C#的扩展方法。

举个小例子:

定义一个静态类StringExtension和静态方法Foo,关键字this.

 public static class StringExtension
    {
        public static void Foo(this string s)
        {
            Console.WriteLine("Foo invoked fro {0}", s);
        }
    }

这样引用该类的命名空间之后,就可以调用Foo方法

string s = "hello";
s.Foo();

等同于

string s = "hello";
StringExtension.Foo(s); //s.Foo();

LINQ的扩展方法的类是System.Linq命名空间下的Enumerable。

调用Where方法时,第一个参数是包含了this的IEnumerable<T>,第二个参数是一个Func<T,bool>委托,它引用一个返回Bool、参数为T的方法。

原文地址:https://www.cnblogs.com/GallopingSnail/p/5887284.html