Last active
May 18, 2021 06:13
-
-
Save Sl4vP0weR/50804ce67becb91a6ba71ceb034e7c51 to your computer and use it in GitHub Desktop.
FieldDelegator
This file contains 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 class FieldDelegator<T> : FieldDelegator where T : Delegate | |
{ | |
public FieldDelegator(FieldInfo field, object owner = null) : base(field, owner) { } | |
public static void Do(FieldInfo fld, object owner = null, T del = null, bool combine = true) => | |
FieldDelegator.Do(fld, owner, del, combine); | |
public void Do(T del, bool combine = true) => Do(Instance, Owner, del, combine); | |
} | |
public class FieldDelegator | |
{ | |
public FieldDelegator(FieldInfo field, object owner = null) | |
{ | |
Instance = field; | |
Owner = owner; | |
} | |
protected FieldInfo Instance; | |
protected object Owner; | |
public static Delegate ConvertDelegate(Type convertTo, Delegate del) => Delegate.CreateDelegate(convertTo, del.Target, del.Method); | |
public delegate Delegate? DelegateAction(Delegate? a, Delegate? b); | |
public static void Do(FieldInfo fld, object owner = null, Delegate? del = null, bool combine = true) => | |
fld.SetValue(owner, (combine ? (DelegateAction)Delegate.Combine : Delegate.Remove) | |
(fld.GetValue(owner) as Delegate, ConvertDelegate(fld.FieldType, del))); | |
public void Do(Delegate del, bool combine = true) => Do(Instance, Owner, del, combine); | |
public static object Invoke(FieldInfo fld, object owner = null, params object[] args) => | |
(fld.GetValue(owner) as Delegate)?.DynamicInvoke(args); | |
public object Invoke(params object[] args) => Invoke(Instance, Owner, args); | |
public static T Invoke<T>(FieldInfo fld, object owner = null, params object[] args) => | |
(T)Invoke(fld, owner, args); | |
public object Invoke<T>(params object[] args) => Invoke<T>(Instance, Owner, args); | |
} |
Author
Sl4vP0weR
commented
May 3, 2021
•
class Program
{
static void Main()
{
var a = new A();
var fld = typeof(A).GetField(nameof(A._e));
var delegator = new FieldDelegator<MyAction>(fld, a);
delegator.Do(SomeAction1);
delegator.Do(SomeAction2);
delegator.Invoke();
delegator.Do(SomeAction1, false);
delegator.Do(SomeAction2, false);
delegator.Invoke();
}
}
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment