比如想要给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);

 

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

相关文章:

  • 2022-12-23
  • 2021-08-18
  • 2021-08-06
  • 2021-11-03
  • 2022-12-23
  • 2021-09-30
  • 2021-10-16
  • 2022-01-12
猜你喜欢
  • 2021-06-23
  • 2021-12-28
  • 2021-07-21
  • 2021-04-14
  • 2021-12-28
  • 2022-12-23
相关资源
相似解决方案