c# - C#中如何判断集合中对象的类型

标签 c# entity-framework reflection

我尝试在 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/

相关文章:

c# - 只释放给后进线程的线程同步(加锁)

c# - 带有菜单/选项卡的 Xamarin Forms 轮播

c# - Linq toEntity contains 不适用于预存储的变量

reflection - 标量反射

c# - 是否可以在 XAML 中绑定(bind) Canvas 的 Children 属性?

c# - 需要帮助在没有 WebBrowser 的情况下从 HTML 评估 Javascript

c# - 在 Entity Framework 中映射/使用内置MySQL函数

c# - 无法使用 Entity Framework 创建 Controller - 无法检索元数据

go - 在 Golang 中无需声明结构即可从接口(interface)获取接口(interface)字段值

c# - 动态执行委托(delegate)