如何使用反射来调用一个重载方法在.NET如何使用、射来、方法、NET

2023-09-02 10:35:22 作者:庸俗且另类.

有没有办法来调用使用反射在.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]);
 
精彩推荐
图片推荐