【问题标题】:Is it possible to 'overeride' (?) the way my delegate wrapper gets invoked? so instead of meAction.Invoke() I could just do meAction()?是否可以“覆盖”(?)我的委托包装器被调用的方式?所以不是 meAction.Invoke() 我可以只做 meAction() 吗?
【发布时间】:2014-03-15 17:21:53
【问题描述】:

我有一个名为SerializedAction的委托包装器

[Serializable]
public class SerializedAction
{
   private Action action;
   public void Add (Action handler) {...}
   public void Remove (Action handler) {...}
   public void Invoke () { Get().Invoke(); }
   public static SerializedAction operator +(SerializedAction action, Action handler) {...}
   public static SerializedAction operator -(SerializedAction action, Action handler) {...}
   private RebuildInvocationList() {...}
   private Action Get() {...}
   ...
}

我已经设法重载了 +/- 运算符,因此我不必显式调用 AddRemove - 但每当我想调用时,我必须调用 Invoke - 我想知道是否有是一种像普通委托一样调用它的方法,即

var meAction = new SerializedAction();
meAction += handler;
meAction(); // instead of meAction.Invoke()?

这有可能吗?

谢谢。

【问题讨论】:

    标签: c# delegates action wrapper invoke


    【解决方案1】:

    不幸的是,这在 C# 中是不可能的。 "()" 语法简单地编译为对 Delagate.Invoke() 的调用;它不是一个可覆盖的运算符。由于普通的 C# 类不能扩展 Delegate 或 MulticastDelegate,因此您无法让编译器允许您在类中使用 () 语法。也就是说,可以通过创建扩展 MulticastDelegate 的类型并将其编译为一个单独的程序集,然后从 C# 代码中引用该程序集,使用原始 IL 执行类似的操作。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多