Extension Method能夠讓你為一個已經存在的類添加方法,而不用去創建一個子類繼承它。
具體做法:
並且前面要加this關鍵字。
下面是例子:
定義一個類來擴展string類:
namespace MyExtension
{
//Extension methods must be defined in a static class
public static class StringExtension
{
// This is the extension method.
// The first parameter takes the "this" modifier
// and specifies the type for which the method is defined.
public static int WordCount(this String str, string msg)
{
Console.WriteLine(msg);
return str.Split(new char[] { ' ', ',', '.', '?' }, StringSplitOptions.RemoveEmptyEntries).Length;
}
}
}
在調用的類中用using MyExtension;先引入名空間,然後就可以用了:
private void Form1_Load(object sender, EventArgs e)
{
string str = "I come from China, and you? Nice to meet you.";
int count = str.WordCount("hello world");
// "hello world" 傳給msg參數
}