[英]Get the actual type from a Type variable
我试图从Type变量中获取一个类型。 例如:
Type t = typeof(String);
var result = SomeGenericMethod<t>();
第二行发生错误,因为t
不是type
,它是变量。 有什么办法让它成为一种类型?
要基于Type创建泛型的实例,可以使用反射来获取要使用的类型的泛型实例,然后使用Activator创建该实例:
Type t = typeof (string); //the type within our generic
//the type of the generic, without type arguments
Type listType = typeof (List<>);
//the type of the generic with the type arguments added
Type generictype = listType.MakeGenericType(t);
//creates an instance of the generic with the type arguments.
var x = Activator.CreateInstance(generictype);
请注意,此处的x
将是一个object
。 要调用它上面的函数,例如.Sort()
,你必须使它成为dynamic
函数。
请注意 ,此代码难以阅读,编写,维护,理由,理解或喜爱。 如果您有任何替代方案需要使用这种结构,请彻底探索这些结构。
编辑 :您还可以转换从Activator
接收的对象,例如(IList)Activator.CreateInstance(genericType)
。 这将为您提供一些功能,而无需诉诸动态。
不,您无法在编译时知道Type
对象的值,这是您需要执行的操作才能将Type
对象用作实际类型。 无论您正在做什么,需要使用该Type
将需要动态地执行此操作,并且不需要在编译时具有已知类型。
使用反射的丑陋的解决方法:
具有泛型方法的类
public class Dummy {
public string WhatEver<T>() {
return "Hello";
}
}
用法
var d = new Dummy();
Type t = typeof(string);
var result = typeof(Dummy).GetMethod("WhatEver").MakeGenericMethod(t).Invoke(d, null);
在类实例化上,请参阅Max的解决方案
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.