1
class Control: Component
{
   // Unique keys for events
   static readonly object mouseDownEventKey = new object();
   static readonly object mouseUpEventKey = new object();
   // Return event handler associated with key
   protected Delegate GetEventHandler(object key) {...}
   // Add event handler associated with key
   protected void AddEventHandler(object key, Delegate handler) {...}
   // Remove event handler associated with key
   protected void RemoveEventHandler(object key, Delegate handler) {...}
   // MouseDown event
   public event MouseEventHandler MouseDown {
      add { AddEventHandler(mouseDownEventKey, value); }
      remove { RemoveEventHandler(mouseDownEventKey, value); }
   }
   // MouseUp event
   public event MouseEventHandler MouseUp {
      add { AddEventHandler(mouseUpEventKey, value); }
      remove { RemoveEventHandler(mouseUpEventKey, value); }
   }
   // Invoke the MouseUp event
   protected void OnMouseUp(MouseEventArgs args) {
      MouseEventHandler handler;
      handler = (MouseEventHandler)GetEventHandler(mouseUpEventKey);
      if (handler != null)
         handler(this, args);
   }
}

Control 类实现了事件的内部存储机制。AddEventHandler 方法将委托值与键关联,GetEventHandler 方法返回当前与键关联的委托,而 RemoveEventHandler 方法将委托作为指定事件的事件处理程序移除。据推测,底层存储机制的设计使得将空委托值与键关联起来是没有成本的,因此未处理的事件不会消耗存储空间。

这段代码和上一段中的解释对我来说没有任何意义。知道这个内部存储机制是什么吗?在上面的段落中,将代表与卑鄙的人联系起来是什么意思?

4

2 回答 2

3

Windows 窗体控件公开大量事件。一个典型的 UI 将由大量这些控件组成。

当您使用标准事件语法时

public event MouseEventHandler MouseDown;

编译器生成addremove方法以及与委托相同类型的私有字段。

这意味着默认情况下会占用大量内存(即使没有订阅事件)。

Windows 窗体控件定义了自己的存储方法,这意味着内存仅用于实际订阅的事件(加上存储委托的对象,例如字典),从而减少了应用程序的整体内存占用。

委托与对象键相关联,例如,如果Mousedown事件发生,它可以查找适用于该事件的委托,以便可以调用它们。

于 2013-04-10T11:24:24.843 回答
0

据我了解,这种存储机制通常是为了维护弱参考模式而创建的。查看这篇文章以深入了解它http://msdn.microsoft.com/en-us/library/aa970850.aspx

于 2013-04-10T11:27:58.993 回答