【问题标题】:C# Instantiate Generic List with Reflected Type InformationC# 使用反射类型信息实例化泛型列表
【发布时间】:2009-11-10 23:06:43
【问题描述】:

我正在尝试执行以下操作:

  1. 在反映具有各种 EntitySet 子集合的 LINQ-to-SQL 对象后给定 TypeInfo,检索集合
  2. 对集合做一些操作

显然,下面的代码无法编译 - 只是在寻找另一种方法来执行此操作[注意,“Facade”是有问题的 L2S 对象)。无法编译的是“itemType”的用法,因为它是一个变量,而不是类型名称,但你明白了:

//itemType is the reflected Type of child object

EntitySet<itemType> list = (EntitySet<itemType>)type.InvokeMember(
                                       info.Name,
                                       BindingFlags.GetProperty,
                                       null,
                                       Facade,
                                       null);


foreach (itemType o in list)
    //do something with o

我想出的最接近的骗子是here,但没有最终的解决方案。

提前感谢您的任何想法。

【问题讨论】:

    标签: linq generics reflection


    【解决方案1】:

    好的,这行得通:

    var list = type.InvokeMember(
                                 info.Name,
                                 BindingFlags.GetProperty,
                                 null,
                                 Facade,
                                 null);
    
    IEnumerable e = list as IEnumerable;
    
    if (e == null)
        continue;
    
    foreach (object o in e)
        //do stuff with o
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-08-19
      • 1970-01-01
      • 2023-03-19
      • 2013-10-03
      • 2011-04-02
      相关资源
      最近更新 更多