The statement var events = GetType().GetEvents();
gets you a list of EventInfo
objects associated with the current type, not the current instance per se. So the EventInfo
object doesn't contain information about the current instance and hence it doesn't know about the wired-up delegates.
To get the info you want you need to get the backing field for the event handler on your current instance. Here's how:
public class MyClass
{
public event EventHandler MyEvent;
public IEnumerable<MethodInfo> GetSubscribedMethods()
{
Func<EventInfo, FieldInfo> ei2fi =
ei => this.GetType().GetField(ei.Name,
BindingFlags.NonPublic |
BindingFlags.Instance |
BindingFlags.GetField);
return from eventInfo in this.GetType().GetEvents()
let eventFieldInfo = ei2fi(eventInfo)
let eventFieldValue =
(System.Delegate)eventFieldInfo.GetValue(this)
from subscribedDelegate in eventFieldValue.GetInvocationList()
select subscribedDelegate.Method;
}
}
So now your calling code can look like this:
class GetSubscribedMethodsExample
{
public static void Execute()
{
var instance = new MyClass();
instance.MyEvent += new EventHandler(MyHandler);
instance.MyEvent += (s, e) => { };
instance.GetSubscribedMethods()
.Run(h => Console.WriteLine(h.Name));
}
static void MyHandler(object sender, EventArgs e)
{
throw new NotImplementedException();
}
}
The output from the above is:
MyHandler
<Execute>b__0
I'm sure you can jig around with the code if you wish to return the delegate rather than the method info, etc.
I hope this helps.