从上面代码可以看出我们客户端调用时无需关心扩展方法在哪儿写的,你只要实例化原始类,扩展方法自动会有的。
扩展方法在C#4.0中是无处不在的,下面我们看看C#内置的扩展方法来更深刻的了解一下:
1publicstaticclassEnumerable23{45publicstaticIEnumerableWhere(thisIEnumerablesource, FuncView Codepredicate);67publicstaticIEnumerableWhere(thisIEnumerablesource, Func predicate);89publicstaticIEnumerableSelect (thisIEnumerablesource, Func selector);1011publicstaticIEnumerableSelect (thisIEnumerablesource, Func selector);1213}
以上就是微软IEnumerable类的扩展方法,所以我们平时用的时候方法后面点.后就能出来怎么多丰富的where,select等方法是扩展方法起的作用。这里只是拿出一点扩展方法来展示了一下。
下面我们写一下string类扩展方法,我们以前判断一个字符串是否null或空时,用系统内置方法string. IsNullOrEmpty(s),我们把这个方法做成扩展方法演示一下:
1publicstaticclassDemo123{45publicstaticboolIsNullOrEmpty(thisstrings)67{89returnstring.IsNullOrEmpty(s);1011}1213}View Code
盖楼回复 X
(您的评论需要经过审核才能显示)