c# - 创建一个哈希集动态的?
问题描述
我需要动态创建一个 HashSet。但是,下面的代码不起作用?
object paramX = 1; // Parameter
var type = paramX.GetType();
var hs = (HashSet<>)Activator.CreateInstance(typeof(HashSet<>).MakeGenericType(type));
// hs has runtime type of HashSet<int> for paramX of an int value
hs.Add(paramX); // Error
hs
具有运行时类型,HashSet<typeof(type)>
但其编译时类型是对象,因此hs.Add(1)
不起作用。
解决方案
System.Type type = typeof(int); // parameter
var hs = Activator.CreateInstance(typeof(HashSet<>).MakeGenericType(type));
要使用它...
((dynamic)hs).Add(1);
你也可以这样做:
dynamic hs = Activator.CreateInstance(typeof(HashSet<>).MakeGenericType(type));
而且没有必要强制转换为动态......
hs.Add(1);
推荐阅读
- linux - 我有一个登录时间的工作脚本,但如果用户未登录,我会收到错误消息
- datastage - 有没有办法比较两个文件并使用数据阶段生成只有字段级别差异的输出?
- jquery - 为什么我的 jquery 展开/折叠行不起作用?
- java - 将 MimeMessage 对象消息转发为 EML 文件中附件的常规转发格式
- java - 这是相对路径还是绝对路径?
- c# - 使用 PublicSign 签名的 .NET 程序集可以在以后进行真实签名吗?
- visual-studio - ASM 的未定义 .data 部分
- python - 将字符串和数组数据从 CSV 文件转换为 tfrecords 时出错
- angular - Angular JWT 包未正确验证我的令牌
- c++ - 关于 Eigen::MatrixXd 逐列计算的问题