创建一个通用的 T带有包含类型的变量的类型实例 [英] Creating a Generic<T> type instance with a variable containing the Type

查看:23
本文介绍了创建一个通用的 T带有包含类型的变量的类型实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有可能实现下面的代码?我知道它不起作用,但我想知道是否有解决方法?

Is it possible to achieve the following code? I know it doesn't work, but I'm wondering if there is a workaround?

Type k = typeof(double);
List<k> lst = new List<k>();

推荐答案

是的,有:

var genericListType = typeof(List<>);
var specificListType = genericListType.MakeGenericType(typeof(double));
var list = Activator.CreateInstance(specificListType);

这篇关于创建一个通用的 T带有包含类型的变量的类型实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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