如何使用反射来调用一个重载方法在.NET [英] How to use Reflection to Invoke an Overloaded Method in .NET

查看:255
本文介绍了如何使用反射来调用一个重载方法在.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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆