public class A<T>
{
public static void B()
{
}
}
Run Code Online (Sandbox Code Playgroud)
我怎么能像这样调用方法B:
Type C = typeof(SomeClass);
A<C>.B()
Run Code Online (Sandbox Code Playgroud)
你需要使用反射.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);
}
}
Run Code Online (Sandbox Code Playgroud)
作为性能优化,您可以使用反射来获取每种类型的委托,然后您可以调用它而无需进一步反映.
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");
Run Code Online (Sandbox Code Playgroud)