2013-09-30 57 views
11

propertyInfo.SetValue()メソッドを使用してリフレクションでオブジェクトプロパティ値を設定しようとしていますが、「オブジェクトがターゲットタイプに一致しません」という例外が発生します。文字列置換値を持つオブジェクトに単純な文字列プロパティを設定しようとしているので、実際には意味がありません(少なくとも私にとって!)。C#Reflection - オブジェクトがターゲットタイプと一致しません

PropertyInfo fieldPropertyInfo = businessObject.GetType().GetProperties().FirstOrDefault(f => f.Name.ToLower() == piecesLeft[0].ToLower()); 
businessObject = fieldPropertyInfo.GetValue(businessObject, null); 

fieldPropertyInfo.SetValue(businessObject, replacementValue, null); 

私は「てBusinessObject」と「replacementValueは」によって、同じタイプの両方であることを確認しました。さらにたくさんのコードがありますので、これは再帰関数内に含まれているが、これはガッツある - ここでのコードスニペットですあなたがbusinessObjectの種類、そのプロパティのないタイプの別の値にてBusinessObject上プロパティの値を設定しようとしている

businessObject.GetType() == replacementValue.GetType() 

答えて

17

propertyinfo値の値を設定しようとしています。明確で簡潔なコードサンプルに感謝 -

PropertyInfo fieldPropertyInfo = businessObject.GetType().GetProperties() 
           .FirstOrDefault(f => f.Name.ToLower() == piecesLeft[0].ToLower()); 

// also you should check if the propertyInfo is assigned, because the 
// given property looks like a variable. 
if(fieldPropertyInfo == null) 
    throw new Exception(string.Format("Property {0} not found", f.Name.ToLower())); 

// you are overwriting the original businessObject 
var businessObjectPropValue = fieldPropertyInfo.GetValue(businessObject, null); 

fieldPropertyInfo.SetValue(businessObject, replacementValue, null); 
+0

ビンゴ:あなたはbusinessObject

PropertyInfo fieldPropertyInfo = businessObject.GetType().GetProperties() .FirstOrDefault(f => f.Name.ToLower() == piecesLeft[0].ToLower()); // The result should be stored into another variable here: businessObject = fieldPropertyInfo.GetValue(businessObject, null); fieldPropertyInfo.SetValue(businessObject, replacementValue, null); 

を上書きしているので、それはのようなものでなければなりません。ありがとう! –

3

:trueを返し、この比較を、やって。

このコードを使用するには、replacementValuepiecesLeft[0]で定義されているフィールドと同じ型である必要がありますが、明らかにその型ではありません。

4

2行目を削除したいと思っています。とにかくそこで何をしているのですか?プロパティの値をbusinessObjectで参照されているオブジェクトからフェッチし、その値を新しい値businessObjectに設定しています。だからこれが本当に文字列のプロパティなら、businessObjectの値は後で文字列の参照になります - そして、それをの設定としてのプロパティとして使用しようとしています!これを行うのはちょっとです:

dynamic businessObject = ...; 
businessObject = businessObject.SomeProperty; // This returns a string, remember! 
businessObject.SomeProperty = replacementValue; 

これはうまくいかないでしょう。

それが何であるかreplacementValueはっきりしていない - それはから実際の置換値を取得するために、置換文字列またはビジネス・オブジェクトのかどうか、私はあなたを疑うのいずれかとします

PropertyInfo fieldPropertyInfo = businessObject.GetType().GetProperties() 
     .FirstOrDefault(f => f.Name.ToLower() == piecesLeft[0].ToLower()); 
fieldPropertyInfo.SetValue(businessObject, replacementValue, null); 

または:

PropertyInfo fieldPropertyInfo = businessObject.GetType().GetProperties() 
     .FirstOrDefault(f => f.Name.ToLower() == piecesLeft[0].ToLower()); 
object newValue = fieldPropertyInfo.GetValue(replacementValue, null); 
fieldPropertyInfo.SetValue(businessObject, newValue, null); 
関連する問題