如何调用与反思的通用扩展方法? [英] How to call a generic extension method with reflection?
本文介绍了如何调用与反思的通用扩展方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我写的扩展方法 GenericExtension
。现在我要调用的扩展方法扩展
。但价值的MethodInfo
总是空。
I wrote the extension method GenericExtension
. Now I want to call the extension method Extension
. But the value of methodInfo
is always 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));
}
}
哪些错误?
Whats wrong?
推荐答案
扩展方法没有连接到类型表格
,它附着在键入 MyClass的
,因此,抓住它关闭的类型:
The extension method isn't attached to the type Form
, it's attached to the type MyClass
, so grab it off that type:
MethodInfo methodInfo = typeof(MyClass).GetMethod("GenericExtension",
new[] { typeof(Form), typeof(string) });
这篇关于如何调用与反思的通用扩展方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文