C#語言從3.0開始增加了一個很特别的功能:擴充方法。
那麼擴充方法起什麼作用呢?很多時候我們想為已經存在的類擴充某些功能,而又沒有必要去繼承該類,甚至有時候這個類根本就不允許繼承,如String類,這時候就可以使用擴充方法來為其擴充功能。
下面舉例說明:
一、我們建立一個類庫如下:
Code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace MethodExtendClasses
{
//此類本身不起什麼作用,隻是在運作時将方法加載到記憶體中
public static class ExtendsString
{
//用this關鍵字修飾了string 關鍵字,表示這個方法是string的擴充方法
public static string SpaceToUnderLine(this string source)
{
char[] chars = source.ToCharArray();
string temp = "";
foreach (char c in chars)
{
if (char.IsWhiteSpace(c))
temp += "_";
else
temp += c;
}
return temp;
}
}
}
然後編譯。
二、建立一個測試用的控制台程式,添加上一個項目的引用,然後将代碼修改如下:
Code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MethodExtendClasses;//此名稱空間為擴充方法所在位置
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string str = "abc dd tt";
str = str.SpaceToUnderLine(); //SpaceToUnderLine()方法就是我們為string增加的擴充方法,此時看起來好像string類多了個方法,其實我們并沒有真正的操作string類
Console.WriteLine(str);
}
}
}
編譯運作,結果為:abc_dd_tt。說明SpaceToUnderLine()方法起到了作用。
總結
我們在進行方法擴充時,需要注意以下幾點:
1. 擴充方法所在類必須是靜态的。
2. 擴充方法必須是靜态的。
3.擴充方法的參數類型必須是要擴充的類型。
4. 參數類型前必須要加this關鍵字。
轉自:http://student.csdn.net/space.php?uid=270457&do=blog&id=43384