[譯文]c#擴展方法(Extension Method In C#)

原文連接:ide

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

介紹spa

擴展方法是C# 3.0引入的新特性。擴展方法使你可以向現有類型「添加」方法,而無需建立新的派生類型、從新編譯或以其餘方式修改原始類型。 擴展方法是一種特殊的靜態方法,但能夠像擴展類型上的實例方法同樣進行調用。code

擴展方法的特性blog

如下包含了擴展方法的基本特性ip

  1. 擴展方法是靜態方法。
  2. 擴展方法的類是靜態類。
  3. .NET中,此方法的參數中必需要有被擴展類做爲第一個參數,此參數前面用this關鍵字修飾。此方法在客戶端做爲一個指定類型的實例調用。
  4. 擴展方法在VS智能提示中顯示。當在類型實例後鍵入「.」會提示擴展方法。
  5. 擴展方法必須在同一命名空間使用,你須要使用using聲明導入該類的命名空間。
  6. 針對包含擴展方法的擴展類,你能夠定義任何名稱。類必須是靜態的。
  7. 若是你想針對一個類型添加新的方法,你不須要有該類型的源碼,就可使用和執行該類型的擴展方法。
  8. 若是擴展方法與該類型中定義的方法具備相同的簽名,則擴展方法永遠不會被調用。

示例代碼get

咱們針對string類型建立一個擴展方法。該擴展方法必須指定String做爲一個參數,在string的實例後鍵入「.」直接調用該擴展方法。源碼

 

在上面的 WordCount()方法裏,咱們傳遞了一個string類型參數,經過string類型的變量調用,換言之經過string實例調用。string

如今咱們建立了一個靜態類和兩個靜態方法。一個用來計算string中詞的個數。另外一個方法計算string中去除空格的全部字符數。it

 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
相關文章
相關標籤/搜索