Initializing events with initializer syntax

前端 未结 4 1119
情书的邮戳
情书的邮戳 2020-12-07 01:57

I often want to write something like this:

new Form
{
    Text = \"Caption\",
    Controls =
    {
        new Button { Text = \"Button 1\", Click = (s, e) =         


        
4条回答
  •  有刺的猬
    2020-12-07 02:46

    I cannot see any reason why they could not have provided this small teaspoon of sugar, I guess they just didn't!

    There is already quite a lot of syntactic sugar involved in events, if simply declare an event on a class without providing your own implementation, the compiler is providing a delegate backing field for you, plus add / remove 'method' implementations. ALso, when you add an event handler, the compiler uses delegate inference, allowing you to simply point to a method, rather than create a delegate that represents the method.

    Interestingly, Mono C# does allow you to add an event handler in an object initializer:

    http://tirania.org/blog/archive/2009/Jul-27-1.html

    Time to switch to Mono ;-)

提交回复
热议问题