public class A<T>
{
public static void B()
{
}
}我怎么能这样调用方法B:
Type C = typeof(SomeClass);
A<C>.B()发布于 2013-10-31 08:57:40
你需要使用反射。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");https://stackoverflow.com/questions/19701455
复制相似问题