[英]C#: How get the actual type from Type variable
给定Type type
参数,如何创建字典: Dictionary<Type, DataCollection<T>>
, where where typeof(T) == type
?
我试过Dictionary<Type, DataCollection<Type>>
,但它不起作用,因为DataCollection<T>
接受T
类型的数据(其中typeof(T) == type
),而不是Type
的数据。
另外,我不能使它通用: Dictionary<T, DataCollection<T>>
因为我希望所有类型都被接受,而不仅仅是单一类型T
你总是可以用这个创建类型:
Type type = typeof(int);
Type typeDC = typeof(DataCollection<>);
var t = typeof(Dictionary<,>);
var x = t.MakeGenericType(type, typeDC.MakeGenericType(type));
object o = Activator.CreateInstance(x);
然后,您需要使用反射来调用o
的方法或将o
传递给强类型方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.