拡張メソッドの使い方
C# 3.0からの追加された仕様で拡張メソッドを使用できるようになった。
thisで使用する型を指定するとその型で拡張メソッドが使える
下記はMyDate型からTextをもっと賢く取得するための拡張メソッドのサンプル
//クラス名はどれでも構わない(出来るだけわかりやすくした方hがいい) public static class MyDateUtil { //追加する拡張メソッド名(MyDate型から使用できる) public static string GetText(this MyDate myDate) { string rtnText = myDate.Text; rtnText = rtnText.Replace("/", "").Replace("_", ""); if (rtnText.Length == 0) { rtnText=dtmDate.Text; } else { rtnText=dtmDate.Value.GetValueOrDefault().ToString("yyyy/MM/dd"); } return rtnText; } }
- MyDate型は日付用カスタムクラスで有る事を前提にする
使用例
MyDate dtmA = new MyDate(); MyDate dtmB = new MyDate(); dtmA.Value = DateTime.now(); dtmA.Text = ""; string strA = dtmA.GetText(); string strB = dtmB.GetText(); 結果 strA <- "2011/01/07" strB <- "____/__/__"
- GcDate型はデフォルトTextが"____/__/__"になっているとする。