如何在编译时不知道类型的情况下调用泛型函数?

123*_*per 3 c# generics

可以说,如果我有如下情况.


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
}
Run Code Online (Sandbox Code Playgroud)

如何在编译时不知道类型的情况下调用泛型函数?

Tim*_*son 11

你需要使用反射:

MethodInfo methodDefinition = GetType().GetMethod("Foo", new Type[] { });
MethodInfo method = methodDefinition.MakeGenericMethod(somethingType);
method.Invoke();
Run Code Online (Sandbox Code Playgroud)

在编写泛型方法时,最好在可能的情况下提供非泛型过载.例如,如果作者Foo<T>()添加了Foo(Type type)重载,则不需要在此处使用反射.

  • 只需一次更正:MethodInfo方法= methodDefinition.MakeGenericMethod(somethingType); (2认同)