Is it possible to call a private delegate by reflection? if so, how? if not, what is the reason?

I am testing a console application in Reflection to call a delegate whose access modifier is private. The code is as follows:

    public class EventPublisher
    {
        private delegate void PrivateDelegate(string message);
        public delegate void PublicDelegate(string message);
    }

    public class PrivateDelegateSubscriber
    {
        public void Subscribe(EventPublisher evPub)
        {
            Type t = typeof(EventPublisher);
            MemberInfo[] privateDelegate = t.GetMember("PrivateDelegate", BindingFlags.NonPublic);

            Delegate delByReflection = Delegate.CreateDelegate((System.Type)privateDelegate.GetValue(0), this, "MethodForPrivateDelegate");
            // how to call the private delegate like public delegate below?

            Delegate delByReflection2 = Delegate.CreateDelegate(typeof(EventPublisher.PublicDelegate), this, "MethodForPrivateDelegate");
            EventPublisher.PublicDelegate delByReflection2_ins = (EventPublisher.PublicDelegate)delByReflection2;
            delByReflection2_ins("test public delegate");
        }

        public void MethodForPrivateDelegate(string message)
        {
            Console.WriteLine("This is from private delegate subscriber, writing: " + message);
        }
    }

I tested a public delegate and it works as expected, but I did not find any way to do this on a private device. My question is the commented code, if there is any way to do this, or the reason it is not possible.

Thanks in advance

+4
source share
1 answer

how to transfer a private delegate, for example, a public delegate?

. - , . , , , .

, DynamicInvoke(). :.

delByReflection.DynamicInvoke("test private delegate");
+2

Source: https://habr.com/ru/post/1676119/


All Articles