如何创建其参数在运行时已知的特定列表类型,然后遍历此列表? [英] How to create specific list type whose parameter is known at runtime and then loop through this list?

查看:55
本文介绍了如何创建其参数在运行时已知的特定列表类型,然后遍历此列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道我可以像这样创建一个只有在运行时才知道类型的对象:

I know I can create an object whose type is known only at run time like this:

Type t = record.GetType();
var src = Activator.CreateInstance(t.BaseType);

  1. 如何在运行时执行类似 List=new List() 的操作?
  2. 假设我像这样使用反射获取子记录列表

  1. How can I do something like List<Record>=new List<Record>() at run time?
  2. Suppose I am getting Child Record list using Reflection like this

var ChildRecorList=src.GetType().GetProperty(propName).GetValue(src, null);

然后我如何使用 foreachfor 循环来遍历它,因为 foreach 仅适用于已知类型列表.它现在适用于 var 类型.有没有办法将反射值转换为在运行时已知值的特定类型(在第 1 点中提到)

and how can then I loop through this using foreach or for loop because foreach only works for known type list. It does now work with var types. Is there way to cast Reflection value to cast at specific type whose value is known at runtime(mentioned in point 1)

推荐答案

您可以尝试在运行时创建泛型类型:

You can try this to create generic type in runtime:

Type genericListType = typeof (List<>);

// if you have more than one generic argumens 
// you can add your types here like typeof(MyClass),typeof(MyClass2)
Type[] genericArguments = { typeof (Record) }; 

// create your generic type with generic arguments
Type myGenericType = genericListType.MakeGenericType(genericArguments);

// and then  you can create your instance
var recordList = Activator.CreateInstance(myGenericType);

// get your property value

recordList = src.GetType().GetProperty(propName).GetValue(src, null);

而且我猜你确定你的类型是一个 List 然后当你创建你的实例时你可以像这样进行转换:

And I guess you sure your type is a List then when you creating your instance you can make a cast like this:

 var recordList = (IList)Activator.CreateInstance(myGenericType);

然后你可以遍历你的列表

Then you can loop through your list

foreach (var item in recordList)
{
    ...
}

这篇关于如何创建其参数在运行时已知的特定列表类型,然后遍历此列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆