平常在寫.Net時常常會用到.Tostring(),這個就是擴充方法,不需要new而是針對參數型態來操作
以下的程式碼是兩個擴充方法,分別是把日期的西元轉民國和數字前面增加一個自定的符號
要把Method轉換成擴充方法必須把Class指定成static
另外第一個參數前面要加上this,this只能放在第一個參數,在呼叫擴充方法時.net會自動判斷參數型態
public static class MyExtension
{
//西元轉民國
public static string MyToDateTime(this DateTime value)
{
string result = value.AddYears(-1911).Year + value.ToString("/MM/dd");
return result;
}
//數字前增加符號
public static string MyToSymbolCurrency(this int value, string formatSymbol)
{
return formatSymbol + value;
}
}
以下是使用方法
Response.Write(DateTime.Now.MyToDateTime()); //103/08/23
int number = 1000;
Response.Write(number.MyToSymbolCurrency("$")); //$1000
請先 登入 以發表留言。