2008年7月24日木曜日

Nullable型とReflection

前回のエントリー「Nullable型のデータバインド」に関連して、ちょっとテスト。
テーマは、Null許可型のプロパティーにリフレクションを使用して、値を操作できるか?

まずは、int?型のプロパティーを持ったクラスを用意。

  1. class Sample  
  2. {  
  3.     private int? id;  
  4.     public int? ID  
  5.     {  
  6.         get { return id; }  
  7.         set { id = value; }  
  8.     }  
  9. }  



リフレクションによるアクセス

  1. static void Main(string[] args)  
  2. {  
  3.     PropertyInfo info = typeof(Sample).GetProperty("ID");  
  4.   
  5.     Sample sample = new Sample();  
  6.     info.SetValue(sample, 1, null);  
  7.     //ID:1  
  8.     Console.WriteLine("ID:{0}", sample.ID);  
  9.   
  10.     info.SetValue(sample, nullnull);  
  11.     //False  
  12.     Console.WriteLine(sample.ID.HasValue);  
  13.   
  14.     //True  
  15.     Console.WriteLine(info.GetValue(sample,null) == null);  
  16.   
  17.     //ID:1  
  18.     sample.ID = 1;  
  19.     Console.WriteLine("ID:{0}", info.GetValue(sample, null));  
  20. }  



拍子抜けするぐらい、予想通りにうまく行きました。これができるのになぜバインディングができない…

0 件のコメント: