输出结果:


从上面代码可以看出我们客户端调用时无需关心扩展方法在哪儿写的,你只要实例化原始类,扩展方法自动会有的。

扩展方法在C#4.0中是无处不在的,下面我们看看C#内置的扩展方法来更深刻的了解一下:

C#4.0语法糖之第四篇: 扩展方法[多图]图片1C#4.0语法糖之第四篇: 扩展方法[多图]图片2
1publicstaticclassEnumerable23{45publicstaticIEnumerableWhere(thisIEnumerablesource, Funcpredicate);67publicstaticIEnumerableWhere(thisIEnumerablesource, Funcpredicate);89publicstaticIEnumerableSelect(thisIEnumerablesource, Funcselector);1011publicstaticIEnumerableSelect(thisIEnumerablesource, Funcselector);1213}
View Code

以上就是微软IEnumerable类的扩展方法,所以我们平时用的时候方法后面点.后就能出来怎么多丰富的where,select等方法是扩展方法起的作用。这里只是拿出一点扩展方法来展示了一下。

下面我们写一下string类扩展方法,我们以前判断一个字符串是否null或空时,用系统内置方法string. IsNullOrEmpty(s),我们把这个方法做成扩展方法演示一下:

C#4.0语法糖之第四篇: 扩展方法[多图]图片1C#4.0语法糖之第四篇: 扩展方法[多图]图片2
1publicstaticclassDemo123{45publicstaticboolIsNullOrEmpty(thisstrings)67{89returnstring.IsNullOrEmpty(s);1011}1213}
View Code