开发者

How to call generic method if I have only Type instance?

开发者 https://www.devze.com 2023-03-22 18:01 出处:网络
class A { pu开发者_如何学Pythonblic static void M<T>() { ... } } ... Type type = GetSomeType();
class A
{
    pu开发者_如何学Pythonblic static void M<T>() { ... }
}

...
Type type = GetSomeType();

Then I need to call A.M<T>() where type == typeof(T).

Reflection?


Yes, you need reflection. For example:

var method = typeof(A).GetMethod("M");
var generic = method.MakeGenericMethod(type);
generic.Invoke(null, null);


Because the type is known at runtime you need to use reflection:

Type type = GetSomeType();
var m = typeof(A)
    .GetMethod("M", BindingFlags.Static | BindingFlags.Public)
    .MakeGenericMethod(type);
m.Invoke(null, null);
0

精彩评论

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