扩展方法使你能够向现有类型“添加”方法,而无需创建新的派生类型、重新编译或以其他方式修改原始类型。
扩展方法是一种特殊的静态方法,但可以像扩展类型上的实例方法一样进行调用。
.Net 框架的扩展方法观摩
最常见的扩展方法是LINQ标准查询运算符,它将查询功能添加到现有的 System.Collections.IEnumerable和System.Collections.Generic.IEnumerable 类型。
在对List做一些筛选时大都会用到Where方法,例如:
List<int> list = new List<int>() { 10, 45, 15, 39, 21, 26 };
var result = list.Where(x => x > 15);
但查看List类时,发现没有where方法,而且这时必需要引命名空间:
using System.Linq;
而且where方法就是Enumerable类里面的,这里的where就是一个IEnumerable的扩展方法
namespace System.Linq
{
public static class Enumerable
{
//。。。。。其他省略
public static IEnumerable<TSource> Where<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate);
}
}
定义和调用扩展方法
- 定义包含扩展方法的静态类。
- 将扩展方法实现为静态方法,并且使其可见性至少与所在类的可见性相同。
- 此方法的第一个参数指定方法所操作的类型;此参数前面必须加上 this 修饰符。
- 在调用代码中,添加 using 指令,用于指定包含扩展方法类的命名空间。
- 和调用类型的实例方法那样调用这些方法。
就是在一个静态类里定义一个静态方法,这个方法的第一个参数要用this修饰,这方法是对其第一个参数进行扩展的方法。扩展方法要对那个对象扩展,该对象就是这个方法的第一个参数,并用this修饰
示例
using System.Linq;
using System.Text;
using System;
namespace CustomExtensions
{
public static class StringExtension
{
public static int WordCount(this String str)
{
return str.Split(new char[] {' ', '.','?'}, StringSplitOptions.RemoveEmptyEntries).Length;
}
}
}
namespace Extension_Methods_Simple
{
using CustomExtensions;
class Program
{
static void Main(string[] args)
{
string s = "The quick brown fox jumped over the lazy dog.";
int i = s.WordCount();
//int i = StringExtension.WordCount(s);//也可以写成这样
System.Console.WriteLine("Word count of s is {0}", i);
}
}
}
总结
因为扩展方法会会污染原有的类,所以在定义时要用命名空间来区分,就像不引用System.Linq,list就没有where方法。