[英]Calling a static method of generic class with a dynamic type c#
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");
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.