标签:c#
扩展方法
不使用扩展方法:
<span style="font-size:10px;">using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ExtraMethod { //抽象出静态StringHelper类 public static class StringHelper { //抽象出来的将字符串第一个字符大写,从第一个到第len个小写,其他的不变的方法 public static string ToPascal(string s,int len) { return s.Substring(0, 1).ToUpper() + s.Substring(1, len).ToLower() + s.Substring(len + 1); } } class Program { static void Main(string[] args) { string s1 = "aSDdAdfGDFSf"; string s2 = "sbfSDffsjG"; Console.WriteLine(StringHelper.ToPascal(s1,3)); Console.WriteLine(StringHelper.ToPascal(s2, 5)); } } }</span>
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ExtraMethod { class Program { static void Main(string[] args) { string s1 = "aSDdAdfGDFSf"; string s2 = "sbfSDffsjG"; Console.WriteLine(s1.ToPascal(3)); Console.WriteLine(s2.ToPascal(5)); } } //扩展类,只要是静态就可以 public static class ExtraClass { //扩展方法--特殊的静态方法--为string类型添加特殊的方法ToPascal public static string ToPascal(this string s, int len) { return s.Substring(0, 1).ToUpper() + s.Substring(1, len).ToLower() + s.Substring(len + 1); } } }
定义扩展方法
1.定义一个静态类以包含扩展方法。
2.该类必须对客户端代码可见。
3.将该扩展方法实现为静态方法,并使其至少具有与包含类相同的可见性。
4.方法的第一个参数指定方法所操作的类型;该参数必须以 this 修饰符开头。
请注意,第一个参数不是由调用代码指定的,因为它表示正应用运算符的类型,并且编译器已经知道对象的类型。 您只需通过 n 为这两个形参提供实参。
标签:c#
原文地址:http://blog.csdn.net/ry513705618/article/details/41603925