c# - 在运行时传递 Type 参数

标签 c# type-parameter

代码

public class Test
{
    public int id{get;set;}
    public Type test{get;set;}
}    

public object Convert<T1, T2>()
{ 
    //do stuff        
}

public void DoConvert()
{
    var a = Convert<Test, Test>(); // This Works

    var t = new Test() { test = typeof(Test); }
    var b = Convert<t.test, t.test>(); // This does not work!
}

问题

如上代码所述。如何使 Convert 方法在运行时定义 T1 和 T2 的地方工作?

最佳答案

必须通过用户反射来获得 Type.MakeGenericType 的结果.假设 Convert 方法是 static 并且在 Temp 类中:

class Temp
{
    public static object Convert<T1, T2>()
    { 
        //do stuff        
    }
}

然后你可以调用:

// assume code to get type1 and type2 dynamically
var type1 = GetGetType1();
var type2 = GetGetType2();

var method =  typeof(Temp).GetMethod("Convert")
                             .MakeGenericMethod(type1, type2);

method.Invoke(null, null);  //assume Convert is static method

关于c# - 在运行时传递 Type 参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15022186/

相关文章:

c# - 有没有办法在不使用 GDI+/WinForms "Graphics"类的情况下检索设备的 DPI?

java - 返回值的 Java 类型参数问题

eclipse - 为什么 Eclipse 编译器会丢失固定类型参数?

java - 在 Java 中,类型变量的边界只能出现在类型变量声明中,对吗?

c# - 其中 t : multiple classes

c# - 创建一个 List<Book> c# 控制台应用程序

c# - 根据条件编辑 ListBoxItem

c# - 在 C# 中同时具有特定参数和参数方法重载的好处

c# - ORM - 数据库架构驱动实体组合还是反之亦然?

generics - 为什么我不能在带有类型参数的特征上添加一揽子暗示?