c# 高级应用 理解扩展方法

367 阅读1分钟

扩展方法的特征

1、它必须在一个非嵌套的,非泛型的静态类中
2、它至少有一个参数
3、第一个参数必须加上this关键字作为前缀
4、第一个参数不能有任何其他的修饰符(比如out或ref)
5、第一个参数的类型不能是指针类型

For Example

public Class Person
{
   public void ShowName(string name)
   {
       Console.WriteLine(name);
   }
}
//扩展方法的创建
public Static Class ExtendPerson
{
   public Static void ShowAge(this Person person,int age)
   {
       Console.WriteLine(age);
   }
}

//扩展方法的使用
Person person = new Person();
person.ShowAge(10);

.Net3.5中的扩展方法

扩展方法你能一种自然的方式将静态方法调用链接到一起,主要体现在Queryable,Enumerable中。
For Example

var collection Enumerable.Range(0,9)
                         .Where(x => x % 2 == 0)
                         .Reverse();
foreach(var element in collection)
{
   Console.WriteLine(element);
}