Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Reflection on this-Object

Tags:

c#

reflection

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

like image 657
Benni Avatar asked Feb 22 '26 06:02

Benni


2 Answers

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?

like image 154
Ani Avatar answered Feb 23 '26 18:02

Ani


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);
    // ...
}
like image 45
LukeH Avatar answered Feb 23 '26 20:02

LukeH



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!