原文链接:
https://www.codeproject.com/Tips/709310/Extension-Method-In-Csharp
介绍
扩展方法是C# 3.0引入的新特性。扩展方法使你能够向现有类型“添加”方法,而无需创建新的派生类型、重新编译或以其他方式修改原始类型。 扩展方法是一种特殊的静态方法,但可以像扩展类型上的实例方法一样进行调用。
扩展方法的特性
以下包含了扩展方法的基本特性
示例代码
我们针对string类型创建一个扩展方法。该扩展方法必须指定String作为一个参数,在string的实例后键入“.”直接调用该扩展方法。
在上面的 WordCount()方法里,我们传递了一个string类型参数,通过string类型的变量调用,换言之通过string实例调用。
现在我们创建了一个静态类和两个静态方法。一个用来计算string中词的个数。另一个方法计算string中去除空格的所有字符数。
1 using System; 2 namespace ExtensionMethodsExample 3 { 4 public static class Extension 5 { 6 public static int WordCount(this string str) 7 { 8 string[] userString = str.Split(new char[] { ‘ ‘, ‘.‘, ‘?‘ }, 9 StringSplitOptions.RemoveEmptyEntries); 10 int wordCount = userString.Length; 11 return wordCount; 12 } 13 public static int TotalCharWithoutSpace(this string str) 14 { 15 int totalCharWithoutSpace = 0; 16 string[] userString = str.Split(‘ ‘); 17 foreach (string stringValue in userString) 18 { 19 totalCharWithoutSpace += stringValue.Length; 20 } 21 return totalCharWithoutSpace; 22 } 23 } 24 }
现在我们创建一个可执行的程序,输入一个string,使用扩展方法来计算所有词数以及string中的所有字符数,结果显示到控制台。
1 using System; 2 namespace ExtensionMethodsExample 3 { 4 class Program 5 { 6 static void Main(string[] args) 7 { 8 string userSentance = string.Empty; 9 int totalWords = 0; 10 int totalCharWithoutSpace = 0; 11 Console.WriteLine("Enter the your sentance"); 12 userSentance = Console.ReadLine(); 13 //calling Extension Method WordCount 14 totalWords = userSentance.WordCount(); 15 Console.WriteLine("Total number of words is :"+ totalWords); 16 //calling Extension Method to count character 17 totalCharWithoutSpace = userSentance.TotalCharWithoutSpace(); 18 Console.WriteLine("Total number of character is :"+totalCharWithoutSpace); 19 Console.ReadKey(); 20 } 21 } 22 }
[译文]c#扩展方法(Extension Method In C#)
原文:http://www.cnblogs.com/wq352/p/6431357.html