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");
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
source
share