首页 > 解决方案 > 创建一个哈希集动态的?

问题描述

我需要动态创建一个 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)不起作用。

标签: c#

解决方案


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

推荐阅读