【问题标题】:How to get the entities from generic EntitySet on run-time without knowing the generic type?如何在不知道泛型类型的情况下在运行时从泛型 EntitySet 获取实体?
【发布时间】:2018-11-28 06:29:22
【问题描述】:

我正在创建一个映射器函数,它将在运行时采用具有未知不同泛型类型的 EntitySet<>,我想获取传入 EntitySet 中的实体并将它们添加到列表中。

我无法访问实体,因为我将 EntitySet 作为对象传入,当我尝试将对象转换为相应类型时失败,因为我不知道 EntitySet 的泛型类型

((EntitySet<XXXX>)dataValues[pInfo.Name]).ToList();

我可以读取泛型 EntitySet 的数据类型,但我不能用它来进行演员表,我不知道如何,也不知道它是否可能!

dataValues[pInfo.Name].GetType().GenericTypeArguments.First()

我不太关心泛型类型,因为我只需要在 EntitySet 中获取集合。

我知道我的问题似乎是重复的,但老实说,我在搜索时发现的结果无法解决我的问题。

我正在使用C#ASP.net

【问题讨论】:

  • EntitySet&lt;TEntity&gt; 实现了非通用的System.Collections.IList 接口,这对你来说是一个选项吗?

标签: c# asp.net generics casting runtime


【解决方案1】:

EntySet 继承自 System.Collections.Generic.ICollection System ICollection 继承自 System.Collections.Generic.IEnumerable 并且 IEnumerable 继承自 System.Collections.IEnumerable。

System.Collections.IEnumerable 不是通用接口。并且可以在 foreach 中使用。

所以你的函数是这样的:

public class Example
{
     public static void EnumEntities( IEnumerable entities )
     {
        foreach( var entity in entities )
        {
            Console.WriteLn( entity.ToString());
        }
     }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-09-19
    • 1970-01-01
    • 2017-03-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多