当在编译时未知类型参数但是在运行时动态获取时,调用泛型方法的最佳方法是什么?
考虑以下示例代码 - 在Example()方法内部,GenericMethod<T>()使用Type存储在myType变量中调用的最简洁方法是什么?
public class Sample
{
public void Example(string typeName)
{
Type myType = FindType(typeName);
// What goes here to call GenericMethod<T>()?
GenericMethod<myType>(); // This doesn't work
// What changes to call StaticMethod<T>()?
Sample.StaticMethod<myType>(); // This also doesn't work
}
public void GenericMethod<T>()
{
// ...
}
public static void StaticMethod<T>()
{
//...
}
}
Run Code Online (Sandbox Code Playgroud) 我上课了
public class A<T>
{
public static string B(T obj)
{
return TransformThisObjectToAString(obj);
}
}
Run Code Online (Sandbox Code Playgroud)
上面使用字符串纯粹是示范性的.我可以在已知/指定的类型上调用这样的静态函数:
string s= A<KnownType>.B(objectOfKnownType);
Run Code Online (Sandbox Code Playgroud)
如果我事先不知道T,我该怎么做这个调用,而是我有一个Type类型的变量来保存类型.如果我这样做:
Type t= typeof(string);
string s= A<t>.B(someStringObject);
Run Code Online (Sandbox Code Playgroud)
我得到这个编译器错误:
Cannot implicitly convert type 't' to 'object'
Run Code Online (Sandbox Code Playgroud)