我尝试在 C# 中使用反射来在运行时确定集合属性中对象的类型。这些对象是 Entity Framework 生成的实体:
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 查询以使其工作
最佳答案
您可以使用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];
// ...
}
关于c# - C#中如何判断集合中对象的类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3538426/