从GenericClass <T>访问静态方法,其中T由Type实例给出

Dan*_*ler 4 c# generics reflection static types

我有一个带静态方法的泛型类,该方法使用type参数:

GenericClass<T>
{
    public static void Method()
    {
        //takes info from typeof(T)
    }
}
Run Code Online (Sandbox Code Playgroud)

现在,我需要访问该静态方法,但不是简单地使用GenericClass<KnownType>.Method().我需要有一个Type实例.所以:

public void OutsiderMethod(Type T)
{
    GenericClass<T>.Method() 
    //it's clear this line won't compile, for T is a Type instance
    //but i want some way to have access to that static method.
}
Run Code Online (Sandbox Code Playgroud)

使用反射,我可能会通过它的字符串名称,使用一些MethodInfo的东西来获得一种方法来调用该方法.这部分是好的,解决了这个问题.但如果可能的话,我很乐意不要将这个名字用作字符串.

任何人???

小智 5

非泛型类的泛型方法比泛型类的非泛型方法更容易访问.

您可以创建一个简单调用实际方法的辅助方法:

void OutsiderMethodHelper<T>()
{
    GenericClass<T>.Method();
}
Run Code Online (Sandbox Code Playgroud)

然后,您可以获取MethodInfofor该方法,而无需通过name-as-string查找:

public void OutsiderMethod(Type T)
{
    Action action = OutsiderMethodHelper<object>;
    action.Method.GetGenericMethodDefinition().MakeGenericMethod(T).Invoke(null, null);
}
Run Code Online (Sandbox Code Playgroud)