当C#编译器解释方法调用时,它必须使用(静态)参数类型来确定实际正在调用的重载。我希望能够以编程方式执行此操作。
如果我有方法(a string
)的名称,声明它的类型(的实例System.Type
)和参数类型列表,我希望能够调用标准库函数并获取MethodInfo
代表该方法的对象,该对象是C#编译器会选择调用。
例如,如果我有
class MyClass {
public void myFunc(BaseClass bc) {};
public void myFunc(DerivedClass dc) {};
}
然后,我想是这样的虚构功能GetOverloadedMethod
上System.Type
MethodInfo methodToInvoke
= typeof(MyClass).GetOverloadedMethod("myFunc", new System.Type[] {typeof(BaseClass)});
在这种情况下methodToInvoke
应该public void myFunc(BaseClass bc)
。
注意:无论是方法GetMethod
和GetMethods
将成为我的目的。它们都不执行任何重载解析。在这种情况下,GetMethod
它仅返回完全匹配项。如果给它更多派生参数,它将什么都不返回。否则,您可能很幸运地获得了不提供任何有用信息的歧义异常。
用Type.GetMethod(String name, Type[] types)
做编程重载决议。这是一个例子:
MethodInfo methodToInvoke = typeof(MyClass)
.GetMethod("myFunc", new System.Type[] { typeof(BaseClass) });
在示例中,methodToInvoke
将myFunc(BaseClass bc)
不是myFunc(DerivedClass dc)
,因为types
数组指定要获取的方法的参数列表。
从MSDN文档开始,Type.GetMethod(String name, Type[] types)
具有两个参数:
name
是要获取的方法的名称,并且types
提供方法参数的顺序,数量和类型。这是一个正在运行的小提琴,它演示了程序重载解决方案。
using System;
using System.Reflection;
public static class Program
{
public static void Main()
{
MethodInfo methodToInvoke = typeof(MyClass)
.GetMethod("myFunc", new System.Type[] { typeof(BaseClass) });
var result = methodToInvoke
.Invoke(new MyClass(), new object[] { new BaseClass() });
Console.WriteLine(result);
}
public class MyClass
{
public static string myFunc(BaseClass bc) {
return "BaseClass";
}
public static string myFunc(DerivedClass dc) {
return "DerivedClass";
}
}
public class BaseClass { }
public class DerivedClass : BaseClass { }
}
输出为BaseClass
。
GetMethod
解决的方法采用params
,更多派生的类,委托和接口实现。这个小提琴演示了所有这些情况。这是电话及其检索的内容。
params
MethodInfo methodToInvoke2 = typeof(MyClass).GetMethod(
"myFunc",
new System.Type[] { typeof(Int32[]) });
将解决此方法
public static string myFunc(params int[] i)
{
return "params";
}
MethodInfo methodToInvoke3 = typeof(MyClass).GetMethod(
"myFunc",
new System.Type[] { typeof(MoreDerivedClass) });
解决采用 MoreDerivedClass
public class BaseClass { }
public class DerivedClass : BaseClass { }
public class MoreDerivedClass : DerivedClass {}
MethodInfo methodToInvoke4 = typeof(MyClass).GetMethod(
"myFunc",
new System.Type[] { typeof(MyDelegate) });
...将检索采用此委托的方法:
public delegate void MyDelegate(string x);
MethodInfo methodToInvoke5 = typeof(MyClass).GetMethod(
"myFunc",
new System.Type[] { typeof(MyImplementation) });
...成功检索了一个方法 MyImplementation
public interface IMyInterface {}
public class MyImplementation : IMyInterface {}
因此,它很健壮,可以GetMethod
在可能无法正常工作的情况下使用重载解析。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句