在对象初始化期间添加事件处理 [英] 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.
推荐答案
这是不可能的,但根据 Roslyn
它是计划的,可能在将来可用。
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屋!
查看全文