From 2b49354fd6b91c72a9599b2a2f78b2e72481b71a Mon Sep 17 00:00:00 2001 From: Chris Cameron Date: Thu, 12 Apr 2018 13:34:32 -0400 Subject: [PATCH 1/2] feat: Reflection util for subscribing to an EventInfo --- ICD.Common.Utils/ReflectionUtils.cs | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/ICD.Common.Utils/ReflectionUtils.cs b/ICD.Common.Utils/ReflectionUtils.cs index 1260bb6..d21b9c9 100644 --- a/ICD.Common.Utils/ReflectionUtils.cs +++ b/ICD.Common.Utils/ReflectionUtils.cs @@ -414,5 +414,26 @@ namespace ICD.Common.Utils throw new InvalidCastException(message, e); } } + + /// + /// Subscribes to the event on the given instance using the handler and callback method. + /// + /// + /// + /// + /// + /// + public static Delegate SubscribeEvent(object instance, EventInfo eventInfo, object handler, MethodInfo callback) + { + if (eventInfo == null) + throw new ArgumentNullException("eventInfo"); + + if (callback == null) + throw new ArgumentNullException("callback"); + + Delegate output = CreateDelegate(eventInfo.EventHandlerType, handler, callback); + eventInfo.AddEventHandler(instance, output); + return output; + } } } From bc1ecf8b8e278e5ac9b8e443e99e668d402b5539 Mon Sep 17 00:00:00 2001 From: Chris Cameron Date: Thu, 12 Apr 2018 14:16:53 -0400 Subject: [PATCH 2/2] feat: Reflection method for unsubscribing from an event. --- ICD.Common.Utils/ReflectionUtils.cs | 25 +++++++++++++++++++++---- 1 file changed, 21 insertions(+), 4 deletions(-) diff --git a/ICD.Common.Utils/ReflectionUtils.cs b/ICD.Common.Utils/ReflectionUtils.cs index d21b9c9..534ca34 100644 --- a/ICD.Common.Utils/ReflectionUtils.cs +++ b/ICD.Common.Utils/ReflectionUtils.cs @@ -418,10 +418,10 @@ namespace ICD.Common.Utils /// /// Subscribes to the event on the given instance using the handler and callback method. /// - /// - /// - /// - /// + /// The instance with the event. Null for static types. + /// The EventInfo for the event. + /// The instance with the callback MethodInfo. Null for static types. + /// The MethodInfo for the callback method. /// public static Delegate SubscribeEvent(object instance, EventInfo eventInfo, object handler, MethodInfo callback) { @@ -435,5 +435,22 @@ namespace ICD.Common.Utils eventInfo.AddEventHandler(instance, output); return output; } + + /// + /// Unsubscribes from the event on the given instance. + /// + /// The instance with the event. Null for static types. + /// The EventInfo for the event. + /// The Delegate to be removed from the event. + public static void UnsubscribeEvent(object instance, EventInfo eventInfo, Delegate callback) + { + if (eventInfo == null) + throw new ArgumentNullException("eventInfo"); + + if (callback == null) + throw new ArgumentNullException("callback"); + + eventInfo.RemoveEventHandler(instance, callback); + } } }