在没有委托变量支持的情况下使用事件会有好处的是什么? [英] What are some cases where it would be advantageous to use an event without having it backed by a delegate variable?
问题描述
我正在阅读Jon Skeet的这篇文章,作为我追求的一部分对代表和事件的深刻理解。
I'm reading this article by Jon Skeet as part of my quest to get a deep understanding of delegates and events.
在本文中,他演示了一个不由代理变量支持的事件,并声明...
In the article he demonstrates an event that isn't backed by a delegate variable and states that...
...有些时候你不想用一个简单的委托
变量来返回事件
。例如,在
的情况下,有很多事件但
只有少数可能被订阅
,您可以从一个关键字
的地图描述该事件代理
目前正在处理它。这就是Windows窗体的
- 这意味着你
可以有大量的事件
,而不会浪费大量的内存
变量通常只有
空值。
...there are times when you don't want to back an event with a simple delegate variable. For instance, in situations where there are lots of events but only a few are likely to be subscribed to, you could have a map from some key describing the event to the delegate currently handling it. This is what Windows Forms does - it means that you can have a huge number of events without wasting a lot of memory with variables which will usually just have null values.
我不完全明白他在说什么。有人可以说出这些例子吗?例如,他用描述事件的一些关键字映射到当前正在处理的代理的意思是什么意思? Windows Forms如何做?
I don't fully understand what he is saying. Can someone flesh out the examples? For instance, what does he mean by having a "map from some key describing the event to the delegate currently handling it"? How does Windows Forms do this?
谢谢!
推荐答案
你可以自己使用相同的类型 - EventHandlerList
。假设你有100个事件 - 通常意味着有100个变量,即使没有人订阅该事件也占用空间。而不是这样, EventHandlerList
是一个位,像 Dictionary< object,EventHandler>
当您首次订阅特定事件时,它只会在其内部数据结构中创建一个条目。
You can use the same type yourself - EventHandlerList
. Suppose you have 100 events - that would normally mean having 100 variables, which would take up space even if no-one ever subscribed to the event. Instead of that, EventHandlerList
is a bit like a Dictionary<object, EventHandler>
- it only creates an entry in its internal data structures when you first subscribe to a particular event.
所以你可能会有这样的一些:
So you might have something like:
// Actual values don't matter; they're just keys
private const string FirstEventKey = "FirstEvent";
private const string SecondEventKey = "SecondEvent";
private readonly EventHandlerList events = new EventHandlerList();
public event EventHandler FirstEvent
{
add { events.AddHandler(FirstEventKey, value); }
remove { events.RemoveHandler(FirstEventKey, value); }
}
public event EventHandler SecondEvent
{
add { events.AddHandler(SecondEventKey, value); }
remove { events.RemoveHandler(SecondEventKey, value); }
}
public void OnFirstEvent(EventArgs e)
{
EventHandler handler = (EventHandler) events[FirstEventKey];
if (handler != null)
{
handler(this, e);
}
}
// Similarly for OnSecondEvent
这篇关于在没有委托变量支持的情况下使用事件会有好处的是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!