传递事件作为一个参数的方法 [英] Pass an event as a parameter to a method
问题描述
可能重复:结果
如何通过事件一种方法?
是否有可能通过一个事件作为一个参数?方法
Is it possible to pass an event as a parameter to a method?
例如,下面的方法所预订的情况下,不工作,并从事件退订:
For example, the following method subscribes to the event, does work, and unsubscribes from the event:
void SubscribeDoAndUnsubscribe<TElement, TEventArgs>(
IEnumerable<TElement> elements,
??? elementEvent)
where TEventArgs: EventArgs
{
EventHandler<TEventArgs> handler = (sender, e) => { /* Handle an event */ };
foreach (var element in elements)
{
// Subscribe somehow
element.elementEvent += handler
}
// Do things
foreach (var element in elements)
{
// Unsubscribe somehow
element.elementEvent -= handler
}
}
客户端代码:
var elements = new [] { new Button(), new Button() };
SubscribeDoAndUnsubscribe(elements, ??? /* e => e.Click */);
如果这是不可能的,我怎么实现在其他方面类似的逻辑?我应通过对与会代表进行订阅/退订方法?
If it's not possible, how do I achieve the similar logic in other ways? Shall I pass pair of delegates for subscribe/unsubscribe methods?
推荐答案
您其实已经发现,事件是不是一流在C#;你无法绕过的事件的数据。您可以委托绕过的与接收器的是通过一个委托一流的对象相关联的方法。你可以通过周围的任何变量的作为(大部分)第一类对象的引用。 (我说大多是因为对变量的引用不能保存在字段中,存储在阵列,等等。他们高度限制相对于其他类型的数据),您可以通过周围的键入的通获取其类型的对象,并通过周围。
You have in fact discovered that events are not "first class" in C#; you cannot pass around an event as data. You can pass around a delegate to a method associated with a receiver as a first-class object by making a delegate. You can pass around a reference to any variable as a (mostly) first-class object. (I say "mostly" because references to variables cannot be stored in fields, stored in arrays, and so on; they are highly restricted compared to other kinds of data.) You can pass around a type by obtaining its Type object and passing that around.
但没有办法直接绕过作为数据的事件,属性,索引,与特定实例相关联的构造函数和析构函数。你能做的最好是让一个委托(或对代表)出了拉姆达的,你建议。或者,得到与事件相关联的反射对象并传递周围,与该实例沿
But there is no way to directly pass around as data an event, property, indexer, constructor or destructor associated with a particular instance. The best you can do is to make a delegate (or pair of delegates) out of a lambda, as you suggest. Or, obtain the reflection object associated with the event and pass that around, along with the instance.
这篇关于传递事件作为一个参数的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!