使用类型的字符串调用模板函数
本文关键字:函数 调用 字符串 类型 | 更新日期: 2023-09-27 17:55:39
我需要调用一个模板函数,如下所示:
void myFunc<T>();
我将模板类型作为字符串,我想使用字符串类型调用该函数。例如,如果我想为异常类型调用它,而不是调用:
myFunc<Exception>()
我需要这样做:
string type = "Exception";
myFunc<type>();
(我需要从 JSON 字符串解析一个对象,并且我将对象的类型获取为字符串)
有没有办法做这样的事情。
谢谢
泛型类型必须在编译类型中已知,以便以经典方式调用泛型方法。
因此,在没有反射的情况下,您需要隐式指定类型myFunc<string>()
。
但是,使用反射可以在运行时指定类型。请考虑以下示例:
class Program
{
static void Main(string[] args)
{
string xyz = "abc";
BindingFlags methodflags = BindingFlags.Static | BindingFlags.Public;
MethodInfo mi = typeof(Program).GetMethod("MyFunc", methodflags);
mi.MakeGenericMethod(xyz.GetType()).Invoke(null, null);
}
public static void MyFunc<T>()
{
Console.WriteLine(typeof(T).FullName);
}
}
MyFunc
打印System.String