2012年1月30日 星期一

C# 擴充方法 - Extensions

因為有需要要把 DataTable 的資料倒出來到 csv 檔案裡面去,
想要有很簡易的使用方式,
於是乎就參考到了 擴充方法 (C# 程式設計手冊) ,
程式寫完之後我就可以直接用 DataTable.ExportCSV 來使用我新增的方法了!
如下圖所示:



可以直接這樣點出來是不是很棒!
那這樣的程式該怎麼寫呢?

其實很簡單,只有兩個重點,如下:
  1. class 必須是 static 的。
  2. function 的第一個參數必須是 this,然後是妳想要擴充的型態,例如這邊我要擴充的是 DataTable 的型態。

看一下下面的範例吧!

public static class DataTableExtensions
{
    public static void ExportCSV(this DataTable dt, string fileName,
        ExportTitleType ett, string split)
    {
        using (StreamWriter sw = new StreamWriter(fileName, false, Encoding.Default))
        {
           
        }
    }

    public static Dictionary<string, string> ToDictionary(this DataTable dt,
        string keyField, string valueField)
    {
        Dictionary<string, string> dic = new Dictionary<string, string>();

        foreach (DataRow dr in dt.Rows)
        {
            string key = dr[keyField].ToString();
            string value = dr[valueField].ToString();

            dic.Add(key, value);
        }

        return dic;
    }
}

這樣有沒有很簡單,又很方便使用!

沒有留言:

張貼留言