列表与LT;>动态创建的结构 [英] List<> of dynamicly created structure

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

问题描述

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

  void Function1(){

TypeBuilder tb = .... // tb是一个值类型
...
类型myType = tb.CreateType();
列表< myType> myTable = new List< myType>();
}

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

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

解决方案

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

 类型listType = typeof(List>); 
类型concreteType = listType.MakeGenericType(myType);

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


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>();
}

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天全站免登陆