比方说,如果我遇到如下情况。
Type somethingType = b.GetType();
// b is an instance of Bar();
Foo<somethingType>(); //Compilation error!!
//I don't know what is the Type of "something" at compile time to call
//like Foo<Bar>();
//Where:
public void Foo<T>()
{
//impl
}
如何在编译时不知道类型的情况下调用泛型函数?
最佳答案
你需要使用反射:
MethodInfo methodDefinition = GetType().GetMethod("Foo", new Type[] { });
MethodInfo method = methodDefinition.MakeGenericMethod(somethingType);
method.Invoke();
编写泛型方法时,最好尽可能提供非泛型重载。例如,如果 Foo<T>()
的作者添加了一个Foo(Type type)
重载,你不需要在这里使用反射。
关于c# - 我应该如何在编译时不知道类型的情况下调用泛型函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3555056/