如何在 .NET 中使用反射调用重载方法 [英] How to use Reflection to Invoke an Overloaded Method in .NET
问题描述
有没有办法在 .NET (2.0) 中使用反射来调用重载方法.我有一个动态实例化从公共基类派生的类的应用程序.出于兼容性考虑,该基类包含 2 个同名方法,一个带参数,一个不带参数.我需要通过 Invoke 方法调用无参数方法.现在,我得到的只是一个错误,告诉我我正在尝试调用一个不明确的方法.
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.
是的,我可以将对象转换为我的基类的实例并调用我需要的方法.最终,这种情况会发生,但目前,内部复杂情况不允许.
Yes, I could just cast the object as an instance of my base class and call the method I need. Eventually that will happen, but right now, internal complications will not allow it.
任何帮助都会很棒!谢谢.
Any help would be great! Thanks.
推荐答案
你必须指定你想要的方法:
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]);
这篇关于如何在 .NET 中使用反射调用重载方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!