【问题标题】:Creating generic type with reflection使用反射创建泛型类型
【发布时间】:2018-03-25 22:59:02
【问题描述】:

我正在我的大学学习 C#,我必须使用反射创建一个通用类实例,但我不知道该怎么做。这是我的代码:

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); 而不使用反射)?

【问题讨论】:

标签: c# reflection


【解决方案1】:

你需要写

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

typeof(MyClass&lt;,&gt;) 返回一个不指定参数的开放泛型MakeGenericType() 然后从它创建一个封闭(或具体)泛型类型,它确实指定了参数。

【讨论】:

  • 你还在用 C#,当你的日常生活是在 Javascript 中?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-09-02
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多