2010-08-21 53 views
2

我正在嘗試在C#中使用反射來確定運行時集合屬性中對象的類型。這些對象是由實體框架生成的實體:如何確定C#中集合中對象的類型

Type t = entity.GetType(); 
PropertyInfo [] propInfo = t.GetProperties(); 
foreach(PropertyInfo pi in propInfo) 
{ 
    if (pi.PropertyType.IsGenericType) 
    { 
     if (pi.PropertyType.GetGenericTypeDefinition() 
      == typeof(EntityCollection<>)) 
     // 'ToString().Contains("EntityCollection"))' removed d2 TimWi's advice 
     // 
     // ---> this is where I need to get the underlying type 
     // ---> of the objects in the collection :-) 
     // etc. 
    } 
} 

如何識別集合所持有的對象的類型?

編輯:上面更新的代碼,將第一.IsGenericType查詢,使其工作

+0

請告訴我你想解決什麼問題?爲什麼你需要知道集合中的類型?我認爲他們不是全部相同的類型? – PatrickSteele 2010-08-21 18:17:04

+0

其實它們是相同的類型。 我需要創建一個新對象並讓用戶設置它的值,但我不知道設計時的類型。因此,使用反射,我將獲取並調用構造函數,最終將新對象添加到適當的集合中。 – Jay 2010-08-21 18:28:07

回答

3

您可以使用GetGenericArguments()檢索集合類型的泛型參數(例如,用於EntityCollection<string>,一般的說法是string)。由於EntityCollection<>總是有一個通用的說法,GetGenericArguments()總是會返回一個單元素數組,所以你可以放心地檢索數組的第一個元素:

if (pi.PropertyType.IsGeneric && 
    pi.PropertyType.GetGenericTypeDefinition() == typeof(EntityCollection<>)) 
{ 
    // This is now safe 
    var elementType = pi.PropertyType.GetGenericArguments()[0]; 

    // ... 
} 
+0

item [0]?你的意思是「GetGenericArguments()」?那不會是空的。 – 2010-08-21 18:33:33

+0

好點柯克,糾正。 我誤解了代碼查詢實體對象(可能是空的)集合的[0]元素與查詢GenericArguments的[0]元素。 – Jay 2010-08-21 18:39:46

+0

謝謝Timwi。唯一的問題是如果該屬性不是泛型類型,則會引發異常。我用你的建議和附加的「if(pi.PropertyType.IsGenericType)」行更新了我的問題。 – Jay 2010-08-21 18:46:59

相關問題