[译文]c#扩展方法(Extension Method In C#)

原文链接:

https://www.codeproject.com/Tips/709310/Extension-Method-In-Csharp

介绍

扩展方法是C# 3.0引入的新特性。扩展方法使你能够向现有类型“添加”方法,而无需创建新的派生类型、重新编译或以其他方式修改原始类型。 扩展方法是一种特殊的静态方法,但可以像扩展类型上的实例方法一样进行调用。

扩展方法的特性

以下包含了扩展方法的基本特性

  1. 扩展方法是静态方法。
  2. 扩展方法的类是静态类。
  3. .NET中,此方法的参数中必须要有被扩展类作为第一个参数,此参数前面用this关键字修饰。此方法在客户端作为一个指定类型的实例调用。
  4. 扩展方法在VS智能提示中显示。当在类型实例后键入“.”会提示扩展方法。
  5. 扩展方法必须在同一命名空间使用,你需要使用using声明导入该类的命名空间。
  6. 针对包含扩展方法的扩展类,你可以定义任何名称。类必须是静态的。
  7. 如果你想针对一个类型添加新的方法,你不需要有该类型的源码,就可以使用和执行该类型的扩展方法。
  8. 如果扩展方法与该类型中定义的方法具有相同的签名,则扩展方法永远不会被调用。

示例代码

我们针对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 }
View Code

现在我们创建一个可执行的程序,输入一个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 } 
View Code

 

posted @ 2017-02-22 22:58  Joan2016  阅读(974)  评论(0编辑  收藏  举报