Cómo usar la Reflexión para Invocar un Método Sobrecargado in.NET


Existe una manera de invocar un método sobrecargado usando reflection en.NET (2.0). Tengo una aplicación que crea instancias dinámicamente de clases que se han derivado de una clase base común. Para fines de compatibilidad, esta clase base contiene 2 métodos del mismo nombre, uno con parámetros y otro sin. Necesito llamar al método sin parámetros a través del método Invoke. En este momento, todo lo que tengo es un error que me dice que estoy tratando de llamar a un método ambiguo.

Sí, I podría simplemente convertir el objeto como una instancia de mi clase base y llamar al método que necesito. Eventualmente eso sucederá, pero en este momento, las complicaciones internas no lo permitirán.

Cualquier ayuda sería genial! Gracias.

Author: Cheeso, 2008-10-22

3 answers

Tienes que especificar qué método quieres:

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]);
 99
Author: Hallgrim,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-07-21 23:55:30

Sí. Cuando invoque el método, pase los parámetros que coincidan con la sobrecarga que desea.

Por ejemplo:

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 } );

Si hace esto al revés(es decir, encontrando el MemberInfo y llamando a Invoke) tenga cuidado de obtener el correcto: la sobrecarga sin parámetros podría ser la primera encontrada.

 16
Author: Keith,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2008-10-21 21:10:49

Utilice la sobrecarga getMethod que toma un Sistema.Escriba [], y pase un tipo vacío [];

typeof ( Class ).GetMethod ( "Method", new Type [ 0 ] { } ).Invoke ( instance, null );
 5
Author: baretta,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2008-10-21 21:09:32