我正在嘗試在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查詢,使其工作
請告訴我你想解決什麼問題?爲什麼你需要知道集合中的類型?我認爲他們不是全部相同的類型? – PatrickSteele 2010-08-21 18:17:04
其實它們是相同的類型。 我需要創建一個新對象並讓用戶設置它的值,但我不知道設計時的類型。因此,使用反射,我將獲取並調用構造函數,最終將新對象添加到適當的集合中。 – Jay 2010-08-21 18:28:07