[NOTE: I don't believe this question is a duplicate of the one linked above, as I explain in the UPDATE below.]
有没有办法使用反射来定义/实例化泛型类?
所以我有一堆类,每个类都拥有一个通用类的实例,该类共享其所有者的类型:
public class GenericClass<T>
{
T Owner { get; set; }
public GenericClass(T owner) { Owner = owner; }
}
public class MyClass
{
private GenericClass<MyClass> myGenericObject;
public MyClass() { myGenericObject = new GenericClass<MyClass>(this); }
}
这是可行的,但是我当然必须明确指定“MyClass”作为 GenericClass 定义中的参数。我希望能够做这样的事情:
private GenericClass<typeof(this)> myGenericObject; // Error: invalid token
无论如何,是否可以根据包含的类在编译时动态指定通用对象的类型?
UPDATE:阅读完来自的答案后these https://stackoverflow.com/questions/12423655/instantiating-a-generic-class-through-reflection-typename 问题 https://stackoverflow.com/questions/1151464/how-to-dynamically-create-generic-c-sharp-object-using-reflection,我了解到我可以实例化一个局部变量,如下所示:
var myGenericObject = Activator.CreateInstance(typeof(GenericClass<>).MakeGenericType(this.GetType()));
但是,当然,this
关键字仅在方法内部可用(因此,例如,我可以将这行代码放在MyClass
)。但我不能用这种方法来定义instance变量(即myGenericObject
,在上面的代码中)。有没有办法动态指定通用实例变量?