对象初始化过程中添加事件处理程序 [英] Add event handler during object initialization
本文介绍了对象初始化过程中添加事件处理程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要通过一个实例的某些类型的方法的(这将在这一刻被创建)。这种类型提供了几个事件,我想订阅过它,所以我的代码如下所示:
I need to pass a instance (which will be created in this very moment) of a certain type to a method. This type offers several events which I'd like to subscribe to too, so my code looks like this:
var instance = new Instance();
instance.OnEvent1 += (sender, args) => {
DoThis();
DoThat();
}
instance.OnEvent2 += (sender, args) => DoThisToo();
instance.OnEvent3...
MyMethod(instance);
现在,是有可能在初始化过程中添加的处理程序?所以,我可以这样写:
Now, is it possible to add the handlers during initialization? So I can write something like this:
MyMethod((MyType)instance => {
instance.OnEvent1 += (sender, args) => {
DoThis();
DoThat();
}
instance.OnEvent2...
});
这是当然只能期望的,因为化妆品的原因。我喜欢我的小代码&安培;可读的。
This is, of course only desired because of cosmetic reasons. I like my code small & readable.
推荐答案
这是不可能的,但现在根据的 罗斯林
该计划,并可能在未来推出。
This is not possible right now but according to Roslyn
it is planned and might be available in the future.
--------------------------------------------------------------------------
| Feature | Example | C# |
-------------------------------------------------------------------------|
| Event initializers | new Customer { Notify += MyHandler }; | Planned |
-------------------------------------------------------------------------|
这篇关于对象初始化过程中添加事件处理程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文