How do I use reflection to invoke a private method?

后端 未结 10 792
说谎
说谎 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

    And if you really want to get yourself in trouble, make it easier to execute by writing an extension method:

    static class AccessExtensions
    {
        public static object call(this object o, string methodName, params object[] args)
        {
            var mi = o.GetType ().GetMethod (methodName, System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance );
            if (mi != null) {
                return mi.Invoke (o, args);
            }
            return null;
        }
    }
    

    And usage:

        class Counter
        {
            public int count { get; private set; }
            void incr(int value) { count += value; }
        }
    
        [Test]
        public void making_questionable_life_choices()
        {
            Counter c = new Counter ();
            c.call ("incr", 2);             // "incr" is private !
            c.call ("incr", 3);
            Assert.AreEqual (5, c.count);
        }
    

提交回复
热议问题