C# 使用动态类型c调用泛型类的静态方法# 公共A类 { 公共静态void B() { } }
我如何像这样调用方法B:C# 使用动态类型c调用泛型类的静态方法# 公共A类 { 公共静态void B() { } },c#,generics,types,C#,Generics,Types,我如何像这样调用方法B: public class A<T> { public static void B() { } } Type C=typeof(SomeClass); A.B() 您需要使用反射MakeGenericType允许您使用特定的泛型参数获取Type,然后您可以根据需要获取并调用其上的任何方法 Type C = typeof(SomeClass); A<C>.B() void Main() { 类型t=类型of(int); 类
public class A<T>
{
public static void B()
{
}
}
Type C=typeof(SomeClass);
A.B()
您需要使用反射MakeGenericType
允许您使用特定的泛型参数获取Type
,然后您可以根据需要获取并调用其上的任何方法
Type C = typeof(SomeClass);
A<C>.B()
void Main()
{
类型t=类型of(int);
类型at=typeof(A)。MakeGenericType(t);
调用(null,新对象[]{“test”});
}
公共A类
{
公共静态无效B(字符串s)
{
Console.WriteLine(s+“”+typeof(T).Name);
}
}
作为性能优化,您可以使用反射为每种类型获取一个委托,然后无需进一步反射即可调用该委托
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);
类型at=typeof(A)。MakeGenericType(t);
Action Action=(Action)Delegate.CreateDelegate(typeof(Action),at.GetMethod(“B”);
行动(“测试”);
您是否可以在第二个代码片段周围添加一些上下文,例如C的声明?您是否打算使用:A.B()代码>C
是一个变量,不是一个类型。@AlexFilipovici no.将来它可能是一个类型的动态列表,并为任何类型调用此方法。
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");