代码之家  ›  专栏  ›  技术社区  ›  Odrade

C:在运行时生成的列表上调用foreach<t>

  •  3
  • Odrade  · 技术社区  · 17 年前

    我正在生成一个带有运行时确定的类型参数的列表。我想调用foreach方法来迭代列表中的项目:

    //Get the type of the list elements
    Type elementType = GetListElementType(finfo);
    
    Type listType = Type.GetType("System.Collections.Generic.List`1[" 
                                  + elementType.FullName + "], mscorlib", true);
    
    //Get the list
    var list = getList.Invoke(null, new Object[] { finfo.GetValue(myObject) });
    
    MethodInfo listForEach = listType.GetMethod("ForEach");
    
    //How do I do this?  Specifically, what takes the place of 'x'?
    listForEach.Invoke(list, new object[] { delegate ( x element )
                                {
                                    //operate on x using reflection
                                }
                            });
    

    给定一个与运行时生成的列表类型中包含的foreach方法相对应的methodinfo,使用匿名方法调用它的正确方法是什么?上面是我的第一步,但不知道如何声明匿名方法参数的类型。

    4 回复  |  直到 17 年前