简体   繁体   English

用反射创建泛型

[英]Creating generic type with reflection

I'm studying C# at my university and I have to create an generic class instance with reflection, but I don't know how to do it exactly. 我正在大学学习C#,我必须使用反射创建一个通用的类实例,但是我不知道该怎么做。 Here's my code: 这是我的代码:

public class MyClass <A, B>
{
    protected A a;
    protected B b;
    public MyClass(A a, B b) { this.a = a; this.b = b; }
}
 static void Main(string[] args)
    {
        Type typ = typeof(MyClass<int, int>);
        object obj = Activator.CreateInstance(typ);

    }

And my question is: how can I pass parameters to constructor and initialize the fields using typeof (something like MyClass c= new MyClass(4, 6); without using reflection)? 我的问题是:如何将参数传递给构造函数并使用typeof初始化字段(类似于MyClass c = new MyClass(4,6);不使用反射)?

You need to write 你需要写

typeof(MyClass<,>).MakeGenericType(type, otherType);

typeof(MyClass<,>) returns an open generic type that does not specify parameters. typeof(MyClass<,>)返回不指定参数的开放通用类型 MakeGenericType() then creates from that a closed (or concrete) generic type , which does specify parameters. 然后, MakeGenericType()从该类型创建一个封闭的(或具体的)泛型类型 ,该泛型类型确实指定了参数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM