为了账号安全,请及时绑定邮箱和手机立即绑定

使用包含Type的变量创建Generic <T>类型实例

使用包含Type的变量创建Generic <T>类型实例

C#
精慕HU 2019-07-26 16:29:35
使用包含Type的变量创建Generic <T>类型实例是否可以实现以下代码?我知道它不起作用,但我想知道是否有解决方法?Type k = typeof(double);List<k> lst = new List<k>();
查看完整描述

3 回答

?
守候你守候我

TA贡献1802条经验 获得超10个赞

就在这里:

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


查看完整回答
反对 回复 2019-07-26
?
慕哥6287543

TA贡献1831条经验 获得超10个赞

更简洁的方法可能是使用通用方法。做这样的事情:

static void AddType<T>()
    where T : DataObject{
    Indexes.Add(typeof(T), new Dictionary<int, T>());}


查看完整回答
反对 回复 2019-07-26
?
江户川乱折腾

TA贡献1851条经验 获得超5个赞

试试这个:

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


查看完整回答
反对 回复 2019-07-26
  • 3 回答
  • 0 关注
  • 546 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信