繁体   English   中英

C#:如何从类型变量中获取实际类型

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM