列表<>动态创建的结构 [英] List<> of dynamically created structure

查看:45
本文介绍了列表<>动态创建的结构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C#中,我想基于动态值类型创建一个列表,例如:

In C# I want to create a list based on a dynamic value type, e.g.:

void Function1() {

  TypeBuilder tb = ....   // tb is a value type
  ...
  Type myType = tb.CreateType();
  List<myType> myTable = new List<myType>();
}

void Function2(Type myType)
{
  List<myType> myTable = new List<myType>();
}

这不会完成,因为List<>想要一个静态定义的类型名称.有什么办法可以解决这个问题?

This won't comple because List<> wants a staticly defined type name. Is there any way to work around this?

推荐答案

您将不得不使用反射来创建列表:

You are going to have to use reflection to create the list:

Type listType = typeof(List<>);
Type concreteType = listType.MakeGenericType(myType);

IList list = Activator.CreateInstance(concreteType) as IList;

这篇关于列表&lt;&gt;动态创建的结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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