简体   繁体   English

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

[英]C#: How get the actual type from Type variable

Given the Type type parameter, How can I create the dictionary: Dictionary<Type, DataCollection<T>> , where where typeof(T) == type ?给定Type type参数,如何创建字典: Dictionary<Type, DataCollection<T>> , where where typeof(T) == type

I tried Dictionary<Type, DataCollection<Type>> , but it doesn't work because DataCollection<T> accepts data of type T (where typeof(T) == type ), not of type Type .我试过Dictionary<Type, DataCollection<Type>> ,但它不起作用,因为DataCollection<T>接受T类型的数据(其中typeof(T) == type ),而不是Type的数据。

Also, I cannot make it generic: Dictionary<T, DataCollection<T>> because I want all types to be accepted, not just a single type T另外,我不能使它通用: Dictionary<T, DataCollection<T>>因为我希望所有类型都被接受,而不仅仅是单一类型T

You can always create the type with this:你总是可以用这个创建类型:

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

You would then need to use reflection to call the methods of o or to pass o to a strongly-typed method.然后,您需要使用反射来调用o的方法或将o传递给强类型方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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