简体   繁体   中英

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

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?

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);
    // ...
}

你需要使用BindingFlags.NonPublic来获取私有方法。

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM