gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 01:08:32 25 4
gpt4 key购买 nike

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);
}
}

作为性能优化,您可以使用反射为每种类型获取一个委托(delegate),然后您无需进一步反射即可调用该委托(delegate)。

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");

关于c# - 使用动态类型调用泛型类的静态方法c#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19701455/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com