Skip to content

Instantly share code, notes, and snippets.

@Sl4vP0weR
Last active May 18, 2021 06:13
Show Gist options
  • Save Sl4vP0weR/50804ce67becb91a6ba71ceb034e7c51 to your computer and use it in GitHub Desktop.
Save Sl4vP0weR/50804ce67becb91a6ba71ceb034e7c51 to your computer and use it in GitHub Desktop.
FieldDelegator
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);
}
@Sl4vP0weR
Copy link
Author

Sl4vP0weR commented May 3, 2021

class Program
{
  public static Action SomeFieldWithDelegate;
  static void Main()
  {
    var fld = typeof(Program).GetField(nameof(SomeFieldWithDelegate));
    var delegator = new FieldDelegator<MyAction>(fld);
    delegator.Do(SomeAction1);
    delegator.Do(SomeAction2);
    SomeFieldWithDelegate.Invoke();
    delegator.Do(SomeAction1, false);
    delegator.Do(SomeAction2, false);
    SomeFieldWithDelegate?.Invoke();
  }
}

@Sl4vP0weR
Copy link
Author

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