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



给定CCD_ 1参数,如何创建词典:Dictionary<Type, DataCollection<T>>,其中typeof(T) == type

我试过Dictionary<Type, DataCollection<Type>>,但它不起作用,因为DataCollection<T>接受T类型的数据(其中typeof(T) == type),而不是Type类型的数据。

此外,我不能使其通用:Dictionary<T, DataCollection<T>>因为我希望所有类型都被接受,而不仅仅是单个类型的Type type0

您可以始终使用以下内容创建类型:

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传递给强类型方法。

最新更新