C# 委托链(delegate chaining)的实现原理 - +和-操作符的背后

admin 百科 13
委托链通过Delegate.Combine和Remove实现,基于MulticastDelegate的_invocationList数组合并与移除,+操作符创建新实例合并调用列表,-操作符逆序查找并移除最后一个匹配项,调用时遍历执行各节点,异常会中断后续调用,需手动遍历GetInvocationList实现容错。

C# 委托链(delegate chaining)的实现原理 - +和-操作符的背后-第1张图片-佛山资讯网

委托链的实现原理,本质上是 Delegate 类对 +- 操作符的重载,底层依赖于 MulticastDelegate 的链式结构和不可变性设计。

委托链的底层数据结构:MulticastDelegate

C# 中所有多播委托(即支持链式调用的委托)都继承自 MulticastDelegate,而它本身又继承自 Delegate。关键区别在于:
- Delegate 表示单个方法调用(Target + Method
- MulticastDelegate 额外维护一个 private readonly object[] _invocationList 字段(.NET Core/.NET 5+ 中为 object?[]),实际存储委托节点数组

这个数组不是动态扩容的列表,而是每次组合时新建数组,体现“不可变性”——这也是委托链线程安全的基础。

+ 操作符:创建新委托链

当写 del1 + del2 时,编译器调用 Delegate.Combine(del1, del2),其逻辑大致如下:

  • del1null,返回 del2(非 null)
  • del2null,返回 del1
  • 若两者都不为 null,且都是 MulticastDelegate 子类,则合并它们的 _invocationList 数组(先拷贝 del1 的全部项,再追加 del2 的全部项)
  • 若任一为单播委托(即普通 Delegate),则将其包装为长度为 1 的数组参与合并

最终返回一个全新的 MulticastDelegate 实例,原委托对象不变。

- 操作符:从链中移除匹配的委托

del1 - del2 对应 Delegate.Remove(del1, del2),行为更精细:

标签: 委托 c# ai 区别 .net gate gate.

发布评论 0条评论)

还木有评论哦,快来抢沙发吧~