gpt4 book ai didi

c# - 如何使用反射调用通用扩展方法?

转载 作者:可可西里 更新时间:2023-11-01 09:00:19 25 4
gpt4 key购买 nike

我写了扩展方法GenericExtension。现在我想调用扩展方法 Extension。但是 methodInfo 的值始终为 null。

public static class MyClass
{
public static void GenericExtension<T>(this Form a, string b) where T : Form
{
// code...
}

public static void Extension(this Form a, string b, Type c)
{
MethodInfo methodInfo = typeof(Form).GetMethod("GenericExtension", new[] { typeof(string) });
MethodInfo methodInfoGeneric = methodInfo.MakeGenericMethod(new[] { c });
methodInfoGeneric.Invoke(a, new object[] { a, b });
}

private static void Main(string[] args)
{
new Form().Extension("", typeof (int));
}
}

怎么了?

最佳答案

扩展方法没有附加到 Form 类型,它附加到 MyClass 类型,所以从那个类型中获取它:

MethodInfo methodInfo = typeof(MyClass).GetMethod("GenericExtension",
new[] { typeof(Form), typeof(string) });

关于c# - 如何使用反射调用通用扩展方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15927028/

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