擴展方法是你能夠向現有類型和自定義類型添加方法,而無需創建新的派生類型或者以其他方式修改原始類型
擴展方法是一個特殊的靜態方法,它定義在一個靜態類中,但是可以在其他類型(我們要擴展的那個類)的對象上像調用實例方法那樣調用,因此通過擴展方法可以在不修改一個類的前提下對一個類進行功能上的補充
創建擴展方法
擴展方法和一般靜態方法定義類似,惟一的區別是在第一個參數的前面加上this關鍵字,同時第一個參數的類型也決定了擴展方法可以擴展的類型
格式
public static 返回類型 擴展方法名稱(this 要擴展的類型sourceObj[,擴展方法參數列表])
擴展方法的特點
1:擴展方法是給現有類型添加一個方法
2:擴展方法通過指定this關鍵字修飾方法的第一個參數
3:擴展方法必須聲明在靜態類中
4:擴展方法通過對象來調用
5:擴展方法可以帶參數
實例
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace _10_ExpandMethod
{
public static class AddClass
{
//擴展現有String類型
public static string GetLower(this String str)
{
return str.ToLower();
}
//擴展自定義的Studengt類型
public static string GetName(this Student stu,string strName)
{
return strName;
}
}
//自定義的Student類型
public class Student
{
}
class Program
{
static void Main(string[] args)
{
string strURL = "HTTP://WWW.BAIDU.COM";
strURL = strURL.GetLower();
Console.WriteLine(strURL);
string strName = "小強";
Student student = new Student();
Console.WriteLine(student.GetName(strName));
Console.ReadKey();
}
}
}
運行效果圖