C#对此对象的反思

Ben*_*nni 2 c# reflection

我完全陷入了反思问题,我认为这不是很大,但我没有找到任何解决方案.

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...
    }
}
Run Code Online (Sandbox Code Playgroud)

界面看起来像这样:

public interface myClassIF {

    void DecideAndCall(string identifier);

}
Run Code Online (Sandbox Code Playgroud)

如果我调用GetMethod("...") - Method,我总是得到一个NullReference.我无法理解这一点,因为在这个项目的另一部分我以前做过这个.但是我在其他类型中使用Refelction而不是"this".

是否有可能在实际的instanciated对象中反映方法?我想我应该是,但我不知道怎么样......

非常感谢!奔奔

Ani*_*Ani 12

要检索的方法是私有的,但无参数Type.GetMethod方法只查找公共方法.尝试使用指定绑定约束的重载:

BindingFlags flags = BindingFlags.Instance | BindingFlags.NonPublic;
MethodInfo mi = GetType().GetMethod(methodName, flags);
Run Code Online (Sandbox Code Playgroud)

我强烈建议不要做这样的事情.对象对自身进行反射是非常不寻常的.你显然失去了类型安全; 例如,如果方法的参数不是"A"or ,那么你提供的样本将会失败"B".虽然我确定你的真实程序更复杂,但你确定你不能以不需要反射的方式重新设计它吗?