Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.4k views
in Technique[技术] by (71.8m points)

c# - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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  |
-------------------------------------------------------------------------|

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...