2
public class A<T>
{
    public static void B()
    {
    }
}

次のようにメソッド B を呼び出す方法:

Type C = typeof(SomeClass);
A<C>.B()
4

1 に答える 1

6

リフレクションを使用する必要があります。MakeGenericType特定のジェネリック引数を使用して を取得し、Type好きなように任意のメソッドを取得して呼び出すことができます。

void Main()
{
    Type t = typeof(int);
    Type at = typeof(A<>).MakeGenericType(t);
    at.GetMethod("B").Invoke(null, new object[]{"test"});
}

public class A<T>
{
    public static void B(string s)
    {
        Console.WriteLine(s+" "+typeof(T).Name);
    }
}

パフォーマンスの最適化として、リフレクションを使用して各タイプのデリゲートを取得し、それ以上のリフレクションなしで呼び出すことができます。

Type t = typeof(int);
Type at = typeof(A<>).MakeGenericType(t);
Action<string> action = (Action<string>)Delegate.CreateDelegate(typeof(Action<string>), at.GetMethod("B"));
action("test");
于 2013-10-31T08:57:40.460 に答える