C#3.0擴充方法

來源:互聯網
上載者:User
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、擴充方法可以帶參數。

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.