I am testing Console application on Reflection to call the delegate whose access modifier is private. The code looks like this:
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 cast to 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 have tested the public delegate and it is working as expected, but I haven't found any way to do it on private delegate. My question is the commented code above if there is any way to do it, or the reason why it is not possible.
Thanks in advance
Aucun commentaire:
Enregistrer un commentaire