C#原始類型擴充方法—this參數修飾符

來源:互聯網
上載者:User

 擴充方法使您能夠向現有類型“添加”方法,而無需建立新的衍生類別型、重新編譯或以其他方式修改原始類型。擴充方法是一種特殊的靜態方法,但可以像擴充類型上的執行個體方法一樣進行調用。對於用 C# 和 Visual Basic 編寫的用戶端代碼,調用擴充方法與調用在類型中實際定義的方法之間沒有明顯的差異。

 擴充方法被定義為靜態方法,但它們是通過執行個體方法文法進行調用的。它們的第一個參數指定該方法作用於哪個類型,並且該參數以 this 修飾符為首碼。僅當您使用 using 指令將命名空間顯式匯入到原始碼中之後,擴充方法才位於範圍中。

 下面的樣本示範為 System.String 類定義的一個擴充方法。請注意,它是在非嵌套、非泛型靜態類內部定義的:

 

 1  namespace ExtensionMethods
2 {
3 public static class MyExtensions
4 {
5 public static int WordCount(this String str)
6 {
7 return str.Split(new char[] { ' ', '.', '?' }, StringSplitOptions.RemoveEmptyEntries).Length;
8 }
9 }
10 }

 

可使用以下 using 指令將 WordCount 擴充方法放入範圍中:
  using ExtensionMethods;
  而且,可以在應用程式中使用以下文法對該擴充方法進行調用:
  string s = "Hello Extension Methods";
  int i = s.WordCount();

  在代碼中,可以使用執行個體方法文法調用該擴充方法。但是,編譯器產生的中繼語言 (IL) 會將代碼轉換為對靜態方法的調用。因此,並未真正違反封裝原則。實際上,擴充方法無法訪問它們所擴充的類型中的私人變數。

 

定義和調用擴充方法:
 1、定義一個靜態類以包含擴充方法。該類必須對用戶端代碼可見。有關可訪問性規則的更多資訊,請參見存取修飾詞(C# 編程指南)。
 2、將該擴充方法實現為靜態方法,並使其至少具有與包含類相同的可見度。
 3、該方法的第一個參數指定方法所操作的類型;該參數必須以 this 修飾符開頭。
 4、在調用代碼中,添加一條 using 指令以指定包含擴充方法類的命名空間。
 5、按照與調用類型上的執行個體方法一樣的方式調用擴充方法。
  請注意,第一個參數不是由調用代碼指定的,因為它表示正應用運算子的類型,並且編譯器已經知道對象的類型。您只需通過 n 為這兩個形參提供實參。

樣本
  下面的樣本在 MyExtensions.StringExtension 類中實現了一個名為 WordCount 的擴充方法。該方法對 String 類進行操作,而該類被指定為第一個方法參數。MyExtensions 命名空間被匯入到應用程式命名空間中,並且該方法是在 Main 方法內調用的。

 

 1 using System.Linq;
2  using System.Text;
3  using System;
4
5 namespace CustomExtensions
6 {
7 //Extension methods must be defined in a static class
8 public static class StringExtension
9 {
10 // This is the extension method.
11 // The first parameter takes the "this" modifier
12 // and specifies the type for which the method is defined.
13 public static int WordCount(this String str)
14 {
15 return str.Split(new char[] {' ', '.','?'}, StringSplitOptions.RemoveEmptyEntries).Length;
16 }
17 }
18 }
19 namespace Extension_Methods_Simple
20 {
21 //Import the extension method namespace.
22 using CustomExtensions;
23 class Program
24 {
25 static void Main(string[] args)
26 {
27 string s = "The quick brown fox jumped over the lazy dog.";
28 // Call the method as if it were an
29 // instance method on the type. Note that the first
30 // parameter is not specified by the calling code.
31 int i = s.WordCount();
32 System.Console.WriteLine("Word count of s is {0}", i);
33 }
34 }
35 }

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.