编写扩展方法

比如想要给sting 类添加一个toPascal()方法  作用是把一个字符串的首字母大写后面全小写  s.ToPascal();

1.添加拓展类(必须是静态的) 2.写拓展的实现方法(也必须是静态的)

例:

public static class ExtraClass{  

public static string ToPascal(this string s){ //参数中this表示是通过实例点出来的方法 string 表示是给stringo类写的拓展方法 s 是形参 表示调用该方法的对象 比如 str.ToPascal() s就是str的引用 return s.Substring(0,1).ToUpper()+s.Substring(1).ToLower(); } public static string ToPascal(this string s,int len){ //重载形式 return s.Substring(0,1).ToUpper()+s.Substring(1,len).ToLower(); } } //写完后就可以直接使用了 string a="dsfdsafsdfdsfasdf";
a.ToUpper(); a.ToPascal(); a.ToPascal(
2);

 

注意: 除非必须 否则不要使用拓展方法 如果命名空间不同 则需要添加引用

posted @ 2013-05-04 17:20  Xdoudou  阅读(192)  评论(0编辑  收藏  举报