views:

7317

answers:

7

There are a group of private methods in my class, and I need to call one dynamically based on an input value. Both the invoking code and the target methods are in the same instance. The code looks like this:

MethodInfo dynMethod = this.GetType().GetMethod("Draw_" + itemType);
dynMethod.Invoke(this, new object[] { methodParams });

In this case, GetMethod() will not return private methods. What BindingFlags do I need to supply to GetMethod() so that it can locate private methods?

A: 

BindingFlags.NonPublic

Khoth
It does not work with NonPublic by itself...
Luis Filipe
A: 

I think you can pass it BindingFlags.NonPublic where it is the GetMethod method.

Armin Ronacher
+2  A: 

Are you absolutely sure this can't be done through inheritance? Reflection is the very last thing you should look at when solving a problem, it makes refactoring, understanding your code, and any automated analysis more difficult.

It looks like you should just have a DrawItem1, DrawItem2, etc class that override your dynMethod.

Bill K
@Bill K: Given other circumstances, we decided not to use inheritance for this, hence the use of reflection. For most cases, we would do it that way.
Jeromy Irvine
+23  A: 

Simply change your code to use the overloaded version of GetMethod that accepts BindingFlags:

MethodInfo dynMethod = this.GetType().GetMethod("Draw_" + itemType, BindingFlags.NonPublic | BindingFlags.Instance);
dynMethod.Invoke(this, new object[] { methodParams });

Here's the BindingFlags enumeration documentation.

~ William Riley-Land

SoloBold
I am going to get myself into so much trouble with this.
Frank Schwieterman
+7  A: 

BindingFlags.NonPublic will not return any results by itself. As it turns out, combining it with BindingFlags.Instance does the trick.

MethodInfo dynMethod = this.GetType().GetMethod("Draw_" + itemType, 
    BindingFlags.NonPublic | BindingFlags.Instance);
Jeromy Irvine
+1  A: 

Could you not just have a different Draw method for each type that you want to Draw? Then call the overloaded Draw method passing in the object of type itemType to be drawn.

Your question does not make it clear whether itemType genuinely refers to objects of differing types.

Peter Hession
A: 

I am getting a ambigiousMatchException for my code below:

Can anybody tell me whats wrong with this?

Type myType = new String(new char[] {'b','a','l','a','j','i'}).GetType(); string[] operations = new string[] { "ToUpper","Trim"};

    foreach (string operation in operations)
    {
        Response.Write("\n" + operation + "  " + myType.GetMethod(operation).Invoke(this,null)); 

    }

Thanks in advance

Balaji B
Welcome to StackOverflow. Please note that SO is structured as a question-and-answer site, rather than a traditional message forum: if you have a new question (which you do), please go ahead and ask a new question here: http://stackoverflow.com/questions/ask
AakashM