public class A<T>
{
public static void B()
{
}
}
次のようにメソッド B を呼び出す方法:
Type C = typeof(SomeClass);
A<C>.B()
リフレクションを使用する必要があります。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");