前回のエントリー「Nullable型のデータバインド」に関連して、ちょっとテスト。
テーマは、Null許可型のプロパティーにリフレクションを使用して、値を操作できるか?
まずは、int?型のプロパティーを持ったクラスを用意。
- class Sample
- {
- private int? id;
- public int? ID
- {
- get { return id; }
- set { id = value; }
- }
- }
リフレクションによるアクセス
- static void Main(string[] args)
- {
- PropertyInfo info = typeof(Sample).GetProperty("ID");
- Sample sample = new Sample();
- info.SetValue(sample, 1, null);
- //ID:1
- Console.WriteLine("ID:{0}", sample.ID);
- info.SetValue(sample, null, null);
- //False
- Console.WriteLine(sample.ID.HasValue);
- //True
- Console.WriteLine(info.GetValue(sample,null) == null);
- //ID:1
- sample.ID = 1;
- Console.WriteLine("ID:{0}", info.GetValue(sample, null));
- }
拍子抜けするぐらい、予想通りにうまく行きました。これができるのになぜバインディングができない…
0 件のコメント:
コメントを投稿