2012-01-18 82 views
0

我有一個對象RenderComponent,它有一個名爲Model的屬性,其類型爲StaticModel。當我得到我的RenderComponentPropertyInfo,然後調用GetValue()時,它給了我一個TargetException,說「對象與目標類型不匹配」。PropertyInfo.GetValue在自定義類上失敗

我會寫一小段代碼樣本來給你失敗的要點。這裏的層次:

public class RenderComponent 
{ 
    StaticModel Model; 
} 

public class StaticModel 
{ 

} 

而且我基本上是這樣:

RenderComponent renderComponent = new RenderComponent(); 
PropertyInfo[] props = type.GetProperties(BindingFlags.Public | BindingFlags.Instance); 

foreach (PropertyInfo info in props) 
{ 
    // I get the exception here 
    Object value = info.GetValue(renderComponent, null); 
} 

我的計劃是當然的要複雜得多,但我還是不明白怎麼可能失敗。我必須錯過簡單的東西。

我得到的異常在這條線:

info.GetValue(obj, null)

infoStaticModelPropertyInfoobj是一個實例RenderComponent。當我停在這個異常處並且在obj上執行監視時,我可以實際地逐步遍歷層次結構,直到獲得我的StaticModel值,並且它存在並具有我期望的數據。

我敢肯定,如果我把我在這個線程中發佈的小代碼示例工作的很好,所以它必須是我在我的引擎中調用它的東西,我只是看不到如何GetValue當obj顯然具有該值時可能會失敗。

這裏是我的截圖調試「OBJ」,並找到StaticModel: enter image description here

和這裏的錯誤,我得到: enter image description here

在這裏,你可以看到的值objinfo,證明我傳遞的對象實例是一個RenderComponent,而我調用GetValue的PropertyInfo是一個靜態模型(它是RenderComponent,你可以第一個圖片中看到:從原來的問題 enter image description here

+0

對不起,'info'的值在哪裏?即使您在第二次捕捉中搜索了信息,您也會同時顯示obj。 – jv42 2012-01-18 09:15:22

+2

爲什麼obj(在上次Watch截圖中)具有Key&Value?不應該是RenderComponent?我認爲你傳遞的是KeyValuePair而不是RenderComponent實例 – sos00 2012-01-18 09:48:41

+0

正確的做法是傳入obj.Value。 – 2012-01-18 13:01:00

回答

0

sos00的評論是正確的回答這個問題。他的評論是:

爲什麼obj(在上次Watch截圖中)有密鑰& Value?不應該是RenderComponent?我認爲你傳遞的是KeyValuePair而不是RenderComponent實例