如何使用Activator.CreateInstance创建一个列表<T>,其中T在运行时是未知的?
2024-08-29 01:27:04
参考网址:https://cloud.tencent.com/developer/ask/185965
using System;
using System.Collections.Generic;
namespace ConsActivator
{
class ActivatorHelper
{
public static void TestMain(string[] args)
{
var s1 = CreateListFromType(typeof(Foo));
var s2 = CreateListFromType(typeof(int));
var fo = new Foo();
var s3 = CreateListFromType(fo.GetType()); Console.WriteLine(s1.ToString());
Console.WriteLine(s2.ToString());
Console.WriteLine(s3.ToString());
Console.WriteLine(fo.GetType().Name);
} static object CreateListFromType(Type t)
{
// Create an array of the required type
Array values = Array.CreateInstance(t, ); // and fill it with values of the required type
for (int i = ; i < ; i++)
{
values.SetValue(CreateFooFromType(t), i);
} // Create a list of the required type, passing the values to the constructor
Type genericListType = typeof(List<>);
Type concreteListType = genericListType.MakeGenericType(t); object list = Activator.CreateInstance(concreteListType, new object[] { values }); // DO something with list which is now an List<t> filled with 50 ts
return list;
} // Create a value of the required type
static object CreateFooFromType(Type t)
{
return Activator.CreateInstance(t);
}
}
class Foo
{
public Foo()
{
}
}
}
最新文章
- 在Windows中安装Memcached
- atitit.设计模式(2) -----查表模式/ command 总结
- 【背景建模】VIBE
- eclipse运行WordCount
- Unity3D TestTool Part _1
- 学习Swift -- 协议(下)
- 左右xcode的重构选项的一些理解
- 开源Math.NET基础数学类库使用(03)C#解析Matlab的mat格式
- linux虚拟文件系统2
- JSP中获取jstl中的数据
- 读书笔记《CSS权威指南》
- DNA序列局部比对(Smith–Waterman algorithm)
- Python黑魔法 --- 异步IO( asyncio) 协程
- 【官档整理】Visual Studio 2017 VS2017 中文离线安装包下载
- Linux 中的 tar
- html5-css的使用强制优先级
- Django2.0的path方法无法使用正则表达式的解决办法
- MySQL的DML常用语法格式
- Windows与Linux 互相访问,挂载过程
- poj 1035 Spell checker ( 字符串处理 )
热门文章
- web服务器获取请求客户端真实地址的方法
- [LeetCode] 222. Count Complete Tree Nodes 求完全二叉树的节点个数
- 第02组 Alpha事后诸葛亮
- NTT&;FFT(快速?变换)
- 推荐一款年轻人交友软件get
- Visual Studio 调试系列3 断点
- 刷完欧拉计划中难度系数为5%的所有63道题,我学会了Rust中的哪些知识点?
- kubeadm安装kubernetes 1.16.2
- 云原生生态周报 Vol. 16 | CNCF 归档 rkt,容器运行时“上古”之战老兵凋零
- Springboot项目中pom.xml的Oracle配置错误问题