如何在 .NET 中使用反射调用重载方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/223495/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to use Reflection to Invoke an Overloaded Method in .NET
提问by Wes P
Is there a way to Invoke an overloaded method using reflection in .NET (2.0). I have an application that dynamically instantiates classes that have been derived from a common base class. For compatibility purposes, this base class contains 2 methods of the same name, one with parameters, and one without. I need to call the parameterless method via the Invoke method. Right now, all I get is an error telling me that I'm trying to call an ambiguous method.
有没有办法在 .NET (2.0) 中使用反射来调用重载方法。我有一个动态实例化从公共基类派生的类的应用程序。出于兼容性考虑,这个基类包含 2 个同名方法,一个有参数,一个没有。我需要通过 Invoke 方法调用无参数方法。现在,我得到的只是一个错误,告诉我我正在尝试调用一个不明确的方法。
Yes, I couldjust cast the object as an instance of my base class and call the method I need. Eventually that willhappen, but right now, internal complications will not allow it.
是的,我可以将对象转换为我的基类的实例并调用我需要的方法。最终这会发生,但现在,内部并发症不允许它发生。
Any help would be great! Thanks.
任何帮助都会很棒!谢谢。
回答by Hallgrim
You have to specify which method you want:
您必须指定所需的方法:
class SomeType
{
void Foo(int size, string bar) { }
void Foo() { }
}
SomeType obj = new SomeType();
// call with int and string arguments
obj.GetType()
.GetMethod("Foo", new Type[] { typeof(int), typeof(string) })
.Invoke(obj, new object[] { 42, "Hello" });
// call without arguments
obj.GetType()
.GetMethod("Foo", new Type[0])
.Invoke(obj, new object[0]);
回答by Keith
Yes. When you invoke the method pass the parameters that match the overload that you want.
是的。当您调用该方法时,传递与您想要的重载相匹配的参数。
For instance:
例如:
Type tp = myInstance.GetType();
//call parameter-free overload
tp.InvokeMember( "methodName", BindingFlags.InvokeMethod,
Type.DefaultBinder, myInstance, new object[0] );
//call parameter-ed overload
tp.InvokeMember( "methodName", BindingFlags.InvokeMethod,
Type.DefaultBinder, myInstance, new { param1, param2 } );
If you do this the other way round(i.e. by finding the MemberInfo and calling Invoke) be careful that you get the right one - the parameter-free overload could be the first found.
如果您以相反的方式执行此操作(即通过查找 MemberInfo 并调用 Invoke),请小心您得到正确的 - 无参数重载可能是第一个找到的。
回答by baretta
Use the GetMethod overload that takes a System.Type[], and pass an empty Type[];
使用接受 System.Type[] 的 GetMethod 重载,并传递一个空的 Type[];
typeof ( Class ).GetMethod ( "Method", new Type [ 0 ] { } ).Invoke ( instance, null );

