How do I use reflection to invoke a private method?

后端 未结 10 862
说谎
说谎 2020-11-22 14:05

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 i

10条回答
  •  孤独总比滥情好
    2020-11-22 14:26

    Read this (supplementary) answer (that is sometimes the answer) to understand where this is going and why some people in this thread complain that "it is still not working"

    I wrote exactly same code as one of the answers here. But I still had an issue. I placed break point on

    var mi = o.GetType().GetMethod(methodName, BindingFlags.NonPublic | BindingFlags.Instance );
    

    It executed but mi == null

    And it continued behavior like this until I did "re-build" on all projects involved. I was unit testing one assembly while the reflection method was sitting in third assembly. It was totally confusing but I used Immediate Window to discover methods and I found that a private method I tried to unit test had old name (I renamed it). This told me that old assembly or PDB is still out there even if unit test project builds - for some reason project it tests didn't built. "rebuild" worked

提交回复
热议问题