Last active
March 24, 2018 11:12
-
-
Save andylshort/fbdc865501c1e08256453ee6a13f8d56 to your computer and use it in GitHub Desktop.
Useful methods for use with delegates
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public static class DelegateUtility | |
{ | |
public static T Cast<T>(Delegate source) where T : class | |
{ | |
return Cast(source, typeof(T)) as T; | |
} | |
public static Delegate Cast(Delegate source, Type type) | |
{ | |
if (source == null) return null; | |
Delegate[] delegates = source.GetInvocationList(); | |
if (delegates.Length == 1) return Delegate.CreateDelegate(type, delegates[0].Target, delegates[0].Method); | |
Delegate[] delegatesDest = new Delegate[delegates.Length]; | |
for (int nDelegate = 0; nDelegate < delegates.Length; nDelegate++) | |
{ | |
delegatesDest[nDelegate] = Delegate.CreateDelegate(type, delegates[nDelegate].Target, delegates[nDelegate].Method); | |
} | |
return Delegate.Combine(delegatesDest); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment