2013-09-30 301 views
11

我試圖使用propertyInfo.SetValue()方法來設置對象屬性值與反射,我得到異常「對象不匹配目標類型」。它沒有任何意義(至少對我來說),因爲我只是試圖在一個字符串替換值的對象上設置一個簡單的字符串屬性。這裏有一個代碼片段 - 這是包含一個遞歸函數所以有一大堆更多的代碼中,但這是膽量:C#反射 - 對象與目標類型不匹配

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.GetType() == replacementValue.GetType() 

回答

17

您正試圖設置propertyinfo值的值。因爲你覆蓋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); 

它應該是這樣的:

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

賓果 - 感謝清晰,簡潔的代碼示例。謝謝! –

3

你試圖在BusinessObject的的屬性的值設置爲businessObject的類型,屬性不是類型的另一個值。

要使此代碼生效,replacementValue需要與piecesLeft[0]定義的字段的類型相同,並且顯然不是那種類型。

4

我懷疑你只是想刪除第二行。無論如何,它在那裏做什麼?您從獲取屬性的值,並將其設置爲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); 
相關問題