实例化一个使用泛型类反射 [英] instantiate a generic class using reflection

查看:531
本文介绍了实例化一个使用泛型类反射的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

[注意:我不相信这个问题是一个上面链接的副本,我在下面的更新说明]

[NOTE: I don't believe this question is a duplicate of the one linked above, as I explain in the UPDATE below.]

有什么办法来定义/使用反射实例化一个泛型类?

Is there any way to define/instantiate a generic class using reflection?

所以我有一堆类,其中每个拥有共享其主人的类型泛型类的一个实例:

So I have a bunch of classes, each of which owns an instance of a generic class that shares the type of its owner:

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定义的说法。我希望能够做这样的事:

This works, but of course I have to explicitly specify "MyClass" as the argument in the GenericClass definition. I'd like to be able to do something like this:

private GenericClass<typeof(this)> myGenericObject; // Error: invalid token



反正是有在编译时动态指定的通用对象的类型的基础上,包含类

Is there anyway to dynamically specify the type of the generic object at compile time, based on the containing class?

更新:来自的这些问题,我才知道,我可以实例化一个局部变量,像这样:

UPDATE: After reading the answers from these questions, I learned that I could instantiate a local variable like so:

var myGenericObject = Activator.CreateInstance(typeof(GenericClass<>).MakeGenericType(this.GetType()));



但是,当然,在这个关键字只有一个方法中可用的(因此,例如,我可以把下面这行代码的 MyClass的的构造函数)。但我不能使用这种方法来定义的实例的变量(即 myGenericObject ,在上面的代码)。有什么办法来动态指定一个泛型实例变量?

but, of course, the this keyword is only available inside a method (so, for example, I could put this line of code in the constructor of MyClass). But I cannot use this approach to define an instance variable (i.e., myGenericObject, in the code above). Is there any way to specify a generic instance variable dynamically?

推荐答案

关于你的更新,你可以通过任何键入 MakeGenericType 。例如,下面的也可以工作:

Regarding your update, you can pass any Type to MakeGenericType. For example, the following also works:

var myObject = new MyClass();

var myGenericObject = Activator.CreateInstance(typeof(GenericClass<>).MakeGenericType(typeof(MyClass)), myObject);

Console.WriteLine(myGenericObject.GetType());



输出:

Outputs:

ConsoleApplication1.GenericClass`1[ConsoleApplication1.MyClass]

myObject.GetType()也做同样的事情:

var myGenericObject = Activator.CreateInstance(typeof(GenericClass<>).MakeGenericType(myObject.GetType()), myObject);

这篇关于实例化一个使用泛型类反射的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆