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

Expressionを使用した例を次に示します。

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 に答える