简体   繁体   中英

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. 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)?

You need to write

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

typeof(MyClass<,>) returns an open generic type that does not specify parameters. MakeGenericType() then creates from that a closed (or concrete) generic type , which does specify parameters.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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