2009-05-14 14 views
6

私はリフレクションを使用してオブジェクトのプロパティを設定しています。異なるプロパティタイプのリフレクションによるオブジェクトのプロパティの設定

これらのプロパティには、String、Nullable(double)、Nullable(long)(ここで山括弧をエスケープする方法はわかりません)などの異なる型があります。これらのプロパティの値は、(文字列、オブジェクト)のペアの辞書から取得されます。

だから、例えば私のクラスには、次のプロパティがあります。

string Description { get; set; } 
Nullable<long> Id { get; set; } 
Nullable<double> MaxPower { get; set; } 

(実際にそこにダース・プロパティに関するものです)と辞書は<「説明」、「説明」>のようなエントリを持つことになり、 < "ID"、123456>、< "MaxPowerに"、20000>

今、私は値を設定するには、次のようなものを使用しています:

foreach (PropertyInfo info in this.GetType().GetProperties()) 
{ 
    if (info.CanRead) 
    { 
     object thisPropertyValue = dictionary[info.Name]; 

     if (thisPropertyValue != null && info.CanWrite) 
     { 
      Type propertyType = info.PropertyType; 

      if (propertyType == typeof(String)) 
      { 
       info.SetValue(this, Convert.ToString(thisPropertyValue), null); 
      } 
      else if (propertyType == typeof(Nullable<double>)) 
      { 
       info.SetValue(this, Convert.ToDouble(thisPropertyValue), null); 
      } 
      else if (propertyType == typeof(Nullable<long>)) 
      { 
       info.SetValue(this, Convert.ToInt64(thisPropertyValue), null); 
      } 
      else 
      { 
       throw new ApplicationException("Unexpected property type"); 
      } 
     } 
    } 
} 

質問は次のとおりです。値を割り当てる前に、実際に各プロパティのタイプをチェックする必要がありますか?プロパティ値に対応するプロパティの型が割り当てられるように、実行できるキャストのようなものはありますか?

理想的には私がのように(働いている可能性があります、私は単純に考えて)、次の何かをできるようにしたいと思います:値がすでにのであれば

  if (thisPropertyValue != null && info.CanWrite) 
     { 
      Type propertyType = info.PropertyType; 

      if (propertyType == typeof(String)) 
      { 
       info.SetValue(this, (propertyType)thisPropertyValue, null); 
      } 
     } 

おかげで、 ステファノ

答えて

10

正しいタイプ、いいえ:何もする必要はありません。彼らは(フロート対int型、など)を右ではないかもしれない場合は、単純なアプローチは次のようになります。

編集ヌル調整後)

Type propertyType = info.PropertyType; 
if (thisPropertyValue != null) 
{ 
    Type underlyingType = Nullable.GetUnderlyingType(propertyType); 
    thisPropertyValue = Convert.ChangeType(
     thisPropertyValue, underlyingType ?? propertyType); 
} 
info.SetValue(this, thisPropertyValue, null); 
+0

私はちょうど(info.SetValueをしようと提案するつもりでしたthis、thisPropertyValue、null);これはより良い解決策であるようです。 – ChrisF

+0

Convert.ChangeTypeメソッドの場合+1。これは、コード内のifを避けるための素晴らしい解決策です。 –

+0

@Marc:ありがとう、これはトリックでした;) @ ChrisF:info.SetValue(this、thisPropertyValue、null)は、テストケースの1つでint型からdouble型への変換を試みるときに例外を発生させました。 –

関連する問題