简体   繁体   English

用动态类型c#调用泛型类的静态方法

[英]Calling a static method of generic class with a dynamic type c#

public class A<T>
{
    public static void B()
    {
    }
}

How I can call method B like this: 我如何像这样调用方法B:

Type C = typeof(SomeClass);
A<C>.B()

You need to use reflection. 您需要使用反射。 MakeGenericType allows you to get the Type with specific generic arguments and then you can get and call any method on it as you like. 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);
    }
}

As a performance optimization you could use reflection to get a delegate for each type which you then can invoke without further reflection. 作为性能优化,您可以使用反射来获取每种类型的委托,然后可以在不进行进一步反射的情况下调用每种类型。

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM