开发者

How should I call the generic function without knowing the type at compile time?

Lets say, If 开发者_如何学编程I have a situation like the following.


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
}

How should I call the generic function without knowing the type at compile time?


You'll need to use reflection:

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

When writing a generic method, it's good practice to provide a non-generic overload where possible. For instance, if the author of Foo<T>() had added a Foo(Type type) overload, you wouldn't need to use reflection here.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜