拡張メソッドを使用して、DateTime 型で年齢計算を利用できるようにする
XmlSerializer を使う (シリアル化編) で Person クラスの年齢の計算がてきとうだったので、この辺を参考にして拡張メソッドを作ってみました。
namespace DateTimeExtensions { public static class GetAgeExtension { public static int GetAge (this DateTime birthDay, DateTime today) { DateTime tempDate = new DateTime (birthDay.Year, 1, 1); tempDate = tempDate.AddDays (today.DayOfYear - 1); return today.Year - birthDay.Year + (birthDay <= tempDate ? 0 : -1); } } }
これでこんな風に書けますね。
// ソースの先頭に以下を追加 // using DateTimeExtensions; // Person の配列を作る var people = Enumerable.Range (0, 5) .Select (index => new { index = index, day = new DateTime (1975 + index, index + 1, index + 1) }) .Select (param => new Person () { Name = string.Format ("{0:ddd}", param.day) + suffix [param.index % 2], Gender = (GenderEnum) (param.index % 2), Birthday = param.day, Age = param.day.GetAge (DateTime.Now) // こんな感じで! }).ToArray ();
トラックバック
- このエントリーにトラックバック:
- http://frog.raindrop.jp/cgi-bin/mt/mt-tb.cgi/2231
コメント