gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 16:19:43 26 4
gpt4 key购买 nike

代码

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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com