C#3.0擴充方法是給現有類型添加一個方法。現在類型既可是基礎資料型別 (Elementary Data Type)(如int,String等),也可以是自己定義的類。
//Demo--1 //擴充基本類型 namespace TestExtensionMethods { // 必須建一個靜態類,用來包含要添加的擴充方法 public static class Extensions { //要添加的擴充方法必須為一個靜態方法 //此方法參數列表必須以this開始 第二個即為要擴充的資料類型,在這裡就是要擴充string類型 //第三個就無所謂了,就是一對象名,名字隨便,符合命名規則即可 //綜合來講,此方法就是要給string類型添加一個叫TestMethod的方法, 此方法返回一個int型的值,即返回調用此方法對象的長度。 public static int TestMethod(this string s) { return s.Length; } } //測試擴充方法類 class Program { static void Main(string[] args) { string str = "Hello Extension Methods"; //調用擴充方法,必須用對象來調用 int len = str.TestMethod(); Console.WriteLine(len); } } } //Demo--2 //擴充自訂類型,同時展示了擴充方法帶參數情況,以及方法重載 namespace TestExtendMethod { public class Student { public string Description() { return "Student............."; } public string Description(string name) { return "the student’s name is "+name; } } // 必須建一個靜態類,用來包含要添加的擴充方法 public static class Extensions { //要添加的擴充方法必須為一個靜態方法 //此方法參數列表必須以this開始 第二個即為要擴充的資料類型,在這裡就是要擴充Student類型 //第三個就無所謂了,就是一對象名,名字隨便,符合命名規則即可 //綜合來講,此方法就是要給Student類型添加一個叫TestMethod的方法,此方法返回一個string型的值 public static string TestMethod(this Student s) { return s.Description(); } //要添加的擴充方法必須為一個靜態方法 //此方法參數列表第一個參數表示要擴充哪一個類,第二個參數才表示此擴充方法的真正參數 //綜合來講,此方法就是要給Student類型添加一個叫TestMethod的方法, 此方法帶有一個string類型的參數,並返回一個string型的值 public static string TestMethod(this Student s,string name) { return s.Description(name); } } //測試擴充方法類 class Program { static void Main(string[] args) { Student stu = new Student(); //調用擴充方法,必須用對象來調用 string mes = stu.TestMethod(); Console.WriteLine(mes); //調用帶參數的擴充方法,只要傳第二個參數就可以了 //因為他的第一個參數其實只是為了表明是擴充哪個資料類型 mes = stu.TestMethod("李沉舟"); Console.WriteLine(mes); } } } |
總結:
1、擴充方法是給現有類型添加一個方法;
2、擴充方法是通過 指定關鍵字this修飾方法的第一個參數;
3、擴充方法必須聲明在靜態類中;
4、擴充方法要通用對象來調用;
5、擴充方法可以帶參數。