2013-02-22 113 views
3

代码通过类型参数在运行时

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的地方工作?

回答

3

必须用户反映与Type.MakeGenericType以获得结果。假设Convert方法是静态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 
+0

Nevermind,managed现在就试试吧! – 2013-02-22 10:51:23

+0

@TheunArbeider:更新了我的安装程序 – 2013-02-22 10:54:56

+0

这似乎是工作,因为我希望它!非常感谢! – 2013-02-22 11:02:42

0

Type.MakeGenericType这里是你的朋友。你不能像运行时那样创建泛型类型,你必须使用反射。但是,那么你会失去静态类型,这是你应该知道的。

+0

护理给予〔实施例。它一直告诉我“无法找到类型或命名空间名称't.test'(你是否缺少使用指令或程序集引用?)即使当我尝试var c = t.test.MakeGenericType() – 2013-02-22 10:47:13

0

如何让Convert方法在运行时定义T1和T2的地方工作?

反射或runtume代码生成是你唯一的选择。在编译的代码

模板必须由编译器来解决。因此,无论是在运行时创建和编译代码(编译器都是运行时的一部分),就像ASP.NET所做的那样;或者您避免编译使用反射(如other answer说明:Type.MakeGenericType允许你采取MyType<>T得到MyType<T>)。

对于泛型方法使用MethodInfo.MakeGenericMethod

相关问题