代码
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/