invocar método no estático por nombre

I've been trying to invoke a method by name but the problem is the method I invoke cannot be static and it needs to be of the current class.

I've tried the way of doing it like this:

public static void InvokeMenuMethod(string methodName, object sender, EventArgs e)
  Type calledType = Type.GetType("MyNamespace.MyClass");
  calledType.InvokeMember(
    methodName,
    BindingFlags.InvokeMethod | BindingFlags.Public | BindingFlags.Static,
    null,
    null,
    new object[] { sender, e }
  );
}

This obviously only works for static members so I tried something like this

public static void InvokeMenuMethod(string methodName, object sender, EventArgs e)
  Type calledType = Type.GetType("this");
  calledType.InvokeMember(
    methodName,
    BindingFlags.InvokeMethod | BindingFlags.Public,
    null,
    null,
    new object[] { sender, e }
  );
}

Pero consigo Must specify binding flags describing the invoke operation required (BindingFlags.InvokeMethod CreateInstance GetField SetField GetProperty SetProperty). Parameter name: bindingFlags error...

So how can I go about doing this?

EDIT:

De modo que:

public void InvokeMenuMethod(string methodName, object sender, EventArgs e) {
    Type.GetType("this").InvokeMember(
        methodName,
        BindingFlags.InvokeMethod,
        null,
        this,
        new object[] { sender, e }
    );
}

Gives a NullReferenceException

Solución: No "this" in Type.GetType("this")

preguntado el 28 de agosto de 11 a las 03:08

¿Has probado BindingFlags.Instance? -

please see my changed code - GetType("this") is giving you the exception because it is wrong... -

2 Respuestas

tratan

 this.GetType().InvokeMember(
    methodName,
    BindingFlags.InvokeMethod,
    null,
    this,
    new object[] { sender, e }
  );

Desde MSDN

If InvokeMethod is specified by itself, BindingFlags.Public, BindingFlags.Instance, and BindingFlags.Static are automatically included

Respondido 28 ago 11, 07:08

Eso es BindingFlags.Default. Once you specify any BindingFlags, you lose the default. - SLaks

@SLaks the above is copy&pasted from MSDN - it says that specifying InveokeMethod by itself includes the other flags, check the link out... - Yahia

@Mark - glad I could help :-) - Yahia

Puede añadir BingingFlags.Instance.

Respondido 28 ago 11, 08:08

Quiere decir BindingFlags.Instance? - Mark Lalor

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.