[英]Get type using reflection
我正在嘗試使用反射獲取我的類的屬性類型,但它返回我唯一的RuntimePropertyInfo - 作為類型的名稱。
我有對象MyObject actualData - 它包含屬性 - “name”作為字符串,“Item”作為我的類型DatumType
當我調試時,我可以看到,actualData有2個屬性,第一個是字符串類型,第二個是DatumType,但是當我使用它時:
string typeName = actualData.getType().getProperty("Item").getType().Name
- 它返回RuntimePropertyInfo,而不是DatumType
你能看出我做錯了什么嗎? 我正在使用C# - .Net 4.0。 非常感謝!
您將獲得PropertyInfo
對象的類型getProperty()
返回。 嘗試
string typeName = actualData.getType().getProperty("Item").PropertyType.Name;
如果您想要通過PropertyInfo
對象當前分配給對象的值的類型,您可以調用:
string typeName = actualData.getType().getProperty("Item").GetValue(actualData, null).GetType().Name;
但在這種情況下你也可以簡單地打電話:
string typeName = actualData.Item.GetType().Name;
該
actualData.getType().getProperty("Item")
檢索PropertyInfo
類型的東西。
如果你再詢問它的類型:
actualData.getType().getProperty("Item").getType()
你得到了你所觀察到的。
我懷疑最后這個getType()
不是必需的。
編輯:有人投了這個答案,這是不公平的imho。 問題是“你能看出我做錯了什么嗎?” 並且將一個getType
過多的答案是正確的。 如果詢問者知道他做錯了什么,那么在PropertyInfo
查找PropertyType
就很容易了。
對於那個贊成這個答案的人:請至少在你下次投票時發表評論。 只有當我們相互學習,而不僅僅是抨擊周圍的每個人時,Stackoverflow才有意義。
GetType()
始終返回當前對象的類型,而不是指向的對象。
在您的情況下,請考慮使用string typeName = actualData.getType().getProperty("Item").PropertyType.Name
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.