使用反射创建泛型类型 [英] Creating generic type with reflection
问题描述
我在我的大学学习 C#,我必须使用反射创建一个通用类实例,但我不知道如何准确地做到这一点.这是我的代码:
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);
}
我的问题是:如何将参数传递给构造函数并使用 typeof 初始化字段(类似于 MyClass c= new MyClass(4, 6); 而不使用反射)?
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<,>).MakeGenericType(type, otherType);
typeof(MyClass<,>)
返回未指定参数的开放泛型类型.MakeGenericType()
然后从中创建一个封闭(或具体)泛型类型,它确实指定了参数.
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.
这篇关于使用反射创建泛型类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!