C# 如何在C中确定集合中对象的类型#

C# 如何在C中确定集合中对象的类型#,c#,entity-framework,reflection,C#,Entity Framework,Reflection,我试图使用C#中的反射在运行时确定集合属性中对象的类型。这些对象是实体框架生成的实体: Type t = entity.GetType(); PropertyInfo [] propInfo = t.GetProperties(); foreach(PropertyInfo pi in propInfo) { if (pi.PropertyType.IsGenericType) { if (pi.PropertyType.GetGenericTypeDefinit

我试图使用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.
    }
}
Type t=entity.GetType();
PropertyInfo[]propInfo=t.GetProperties();
foreach(propInfo中的属性信息pi)
{
if(pi.PropertyType.IsGenericType)
{
if(pi.PropertyType.GetGenericTypeDefinition()
==类型(EntityCollection))
//“ToString().Contains(“EntityCollection”)”删除了d2 TimWi的建议
//
//-->这就是我需要获取底层类型的地方
//-->集合中对象的名称:-)
//等等。
}
}
如何识别集合所持有的对象的类型


编辑:更新上面的代码,首先添加.IsGenericType查询以使其工作

您可以使用
GetGenericArguments()
检索集合类型的通用参数(例如,对于
EntityCollection
,通用参数是
string
)。由于
EntityCollection
始终有一个泛型参数,
GetGenericArguments()
将始终返回单个元素数组,因此您可以安全地检索该数组的第一个元素:

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

    // ...
}
if(pi.PropertyType.IsGeneric&&
pi.PropertyType.GetGenericTypeDefinition()==typeof(EntityCollection))
{
//现在安全了
var elementType=pi.PropertyType.GetGenericArguments()[0];
// ...
}

您试图解决的问题是什么?为什么您需要知道集合中的类型?我想他们不都是同一类型的?实际上他们是同一类型的。我需要创建一个新对象并让用户设置它的值,但在设计时我不知道它的类型。因此,使用反射,我将获取并调用构造函数,最终将新对象添加到适当的集合中。项[0]?你是说“GetGenericArguments()”吗?那不会是空的,好的,柯克,更正。我误解代码是查询实体对象集合的[0]元素(可能是空的)而不是查询一般参数的[0]元素。谢谢Timwi。唯一的问题是,如果属性不是泛型类型,则会引发异常。我用你的建议和额外的“if(pi.PropertyType.IsGenericType)”行更新了我的问题。