views:

19

answers:

2

I have the following code used to avoid a switch statement to decide which method to invoke, and it works with just the BindingFlags flags I have set, without InvokeMethod. What is InvokeMethod actually meant for and why is it not needed in the following code:

public enum PublishMethods
{
    Method1,
    Method2,
    Method3
}
private void Form1_Load(object sender, EventArgs e)
{
    InvokePublishMethod(PublishMethods.Method2);
}
private void InvokePublishMethod(PublishMethods publishMethod)
{
    var publishMethodsType = this.GetType();
    var method = publishMethodsType.GetMethod("Publish" + publishMethod, BindingFlags.NonPublic | BindingFlags.Instance);
    method.Invoke(this, null);
}
private void PublishMethod2()
{
    MessageBox.Show("Method2!");
}
+1  A: 

InvokeMethod isn't used by GetMethod, but it is used when you pass a BindingFlags to Type.InvokeMember.

BindingFlags is a strange kind of enum that combines three separate pieces of functionality (according to MSDN, 'accessibility', 'binding argument' and 'operation'). These three pieces of functionality don't make sense wherever a BindingFlags parameter is needed.

Tim Robinson
Aah, so I don't need `GetMethod` to invoke it, just `InvokeMethod`. Nice! In this case, however, I prefer `GetMethod` first so I can construct an error message if the method doesn't exist.
ProfK
+1  A: 

From the MSDN the InvokeMethod member:

Specifies that a method is to be invoked. This must not be a constructor or a type initializer.

It's used by the InvokeMember method.

ChrisF