Is it possible to get the private event of a class using reflection? the below code fails to get the event:
//class having a private Event.
public class Sample
{
private delegate void MyDelegate(string ip4);
private event MyDelegate MyEvent;
}
internal class Program
{
private static void Main(string[] args)
{
//try getting the non-public event
EventInfo[] events = typeof (Sample).GetEvents(BindingFlags.NonPublic);
Console.WriteLine(events.Length); //it's 0
var evt = typeof (Sample).GetEvent("MyEvent", BindingFlags.NonPublic); //evt is null
}
}
You need also specify BindingFlags.Instance
..
var evt = typeof (Sample)
.GetEvent("MyEvent", BindingFlags.NonPublic | BindingFlags.Instance); //evt is null
var evt = typeof(Sample).GetEvent("MyEvent", BindingFlags.NonPublic | BindingFlags.Instance);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.