C#扩展方法(Extend Method)
扩展方法就是在不更改原来类的基础上,为类添加方法。
- 扩展方法所在的类必须声明为static。
- 扩展方法必须声明为public和static。
- 扩展方法的第一个参数必须包含关键字this,并且在后面指定扩展的类的名称。
- 虽然是静态方法,但是这个扩张方法是为某个类扩展的,只能由这个类的对象调用。
public static class 类名
{
public static 返回值 方法名(this 要扩展的类型 对象名[,参数列表])
{
}
}
static class Extend
{
public static TSource Test123<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate)
{
foreach (TSource item in source)
{
if (predicate(item))
{
return (item);
}
}
throw new Exception("未找到!");
}
}
List<int> ints =new List<int> { 1,2,3,4,5,6 };
int nRet = ints.Test123(o => o > 5);//nRet=6