4

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

GenericClass<T>
{
    public static void Method()
    {
        //takes info from typeof(T)
    }
}

现在,我需要访问该静态方法,而不是简单地使用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.
}

使用反射,我可能可以使用一些 MethodInfo 的东西通过它的字符串名称来调用该方法。这部分好,解决了问题。但如果可能的话,我希望不必将名称用作字符串。

任何人???

4

2 回答 2

5

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

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

void OutsiderMethodHelper<T>()
{
    GenericClass<T>.Method();
}

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

public void OutsiderMethod(Type T)
{
    Action action = OutsiderMethodHelper<object>;
    action.Method.GetGenericMethodDefinition().MakeGenericMethod(T).Invoke(null, null);
}
于 2013-04-10T16:57:47.043 回答
0

这是一个使用表达式的示例:

public static class GenericHelper
{
    public static object Invoke(Expression<Action> invokeMethod, object target, Type genericType, params object[] parameters)
    {
        MethodInfo methodInfo = ParseMethodExpression(invokeMethod);
        if (!methodInfo.DeclaringType.IsGenericType)
            throw new ArgumentException("The method supports only generic types");
        Type type = methodInfo.DeclaringType.GetGenericTypeDefinition().MakeGenericType(genericType);
        MethodInfo method = type.GetMethod(methodInfo.Name);
        return method.Invoke(target, parameters);
    }

    public static object Invoke(Expression<Action> invokeMethod, Type genericType, params object[] parameters)
    {
        return Invoke(invokeMethod, null, genericType, parameters: parameters);
    }

    private static MethodInfo ParseMethodExpression(LambdaExpression expression)
    {
        Validate.ArgumentNotNull(expression, "expression");
        // Get the last element of the include path
        var unaryExpression = expression.Body as UnaryExpression;
        if (unaryExpression != null)
        {
            var memberExpression = unaryExpression.Operand as MethodCallExpression;
            if (memberExpression != null)
                return memberExpression.Method;
        }
        var expressionBody = expression.Body as MethodCallExpression;
        if (expressionBody != null)
            return expressionBody.Method;
        throw new NotSupportedException("Expession not supported");
    }
}

方法调用将如下所示:

GenericHelper.Invoke(() => GenericClass<object>.Method(), typeof(string));
于 2013-04-11T04:46:21.097 回答