Benni
Benni

Reputation: 141

C# Reflection on this-Object

i totaly got stuck in a Reflection Problem, i think it isn't real big, but i don't find any solution for this.

public class myClass : myClassIF {

    public myClass() { }

    private void doSomething_A() {
        //...
    }

    private void doSomething_B() {
        //...
    }

    public void DecideAndCall(string identifier) {
        string methodName = "doSomething_" + identifier;
        MethodInfo mi = this.GetType().GetMethod(methodName); //here i got a NullReference??
        //here should be the Invocation of the Method and so on...
    }
}

The Interface looks this way:

public interface myClassIF {

    void DecideAndCall(string identifier);

}

If i call the GetMethod("...")-Method, i always got a NullReference. I can't understand this, because in an other Part of this Project i've done this before. But there i used Refelction to an other Type not to "this".

Is it possible to Reflect Methods in the actually instanciated Object? I think i'd should be, but i don't know how...

Many Thanks! Benni

Upvotes: 2

Views: 471

Answers (4)

StuartLC
StuartLC

Reputation: 107277

Since the methods are private, you need to use the overload taking BindingFlags

MethodInfo mi = typeof(myClass).GetMethod(methodName, BindingFlags.Instance | BindingFlags.NonPublic); 

This is discussed in more detail here

Upvotes: 1

Ani
Ani

Reputation: 113442

The method you want to retrieve is private, but the parameterless Type.GetMethod method only looks for public methods. Try the overload that lets you specify binding-constraints:

BindingFlags flags = BindingFlags.Instance | BindingFlags.NonPublic;
MethodInfo mi = GetType().GetMethod(methodName, flags);

I would strongly recommend against doing something like this though. It's highly unusual for an object to perform reflection on itself. You obviously lose type-safety; for example, your provided sample will fail spectacularly if the argument to the method is something other than "A" or "B". Although I'm sure your real program is more complicated, are you sure you can't redesign this in a way that doesn't require reflection?

Upvotes: 12

gbvb
gbvb

Reputation: 886

YOu need to use the BindingFlags.NonPublic to get to private methods.

Upvotes: 2

LukeH
LukeH

Reputation: 269438

The methods you're interested in are private, so you'll need to specify BindingFlags.NonPublic in your arguments:

public void DecideAndCall(string identifier)
{
    string methodName = "doSomething_" + identifier;

    BindingFlags flags = BindingFlags.Instance | BindingFlags.NonPublic;
    MethodInfo mi = this.GetType().GetMethod(methodName, flags);
    // ...
}

Upvotes: 2

Related Questions