[英]Construct an instance of a concrete type of a generic, using reflection at runtime
考虑以下类别:
public class GenericClass<T>
{
public T Argument;
}
第二个类引用并使用GenericClass:
public class ClientClass
{
GenericClass<T> genclass = new GenericClass<T>();
}
我的问题是我在编译时不知道T的类型。 我在运行时使用反射来获取T的类型。在实例化GenericClass
是否可能以某种方式使用参数化表达式?
是的,但是您必须使用反射来构建您要查找的实际类型。
首先,您需要使用typeof
运算符来获取开放的泛型:
var openType = typeof(GenericClass<>);
接下来,您需要构建所需的特定泛型。 假设您想要的类型T存储在变量中,请type
:
var closedType = openType.MakeGenericType(type);
object instance = Activator.CreateInstance(closedType);
但是,正如xanatos在评论中指出的那样,您应该意识到这会导致object
类型的成员。 为了能够在没有反射的情况下操纵对象,您有两种选择。
GenericClass
自GenericClass<T>
的父类GenericClass
,并在其上包含所有通用的方法。 (即GenericClass
包含不需要使用T
。 IInterface
,然后在T
上添加一个限制, where T : IInterface
。 然后,您可以将instance
为GenericClass<IInterface>
并以这种方式进行操作。 显然,在这种情况下, type
必须实现IInterface
。 当然,您也可以仅保留object
引用并仅使用反射对其进行操作,或者使用dynamic
方法后期绑定任何方法调用-但是,这将在后台使用反射。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.