Initializing events with initializer syntax

前端 未结 4 1121
情书的邮戳
情书的邮戳 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:51

    Try simply assigning an event:

    Click = (o,e) => {  }
    

    Doesn't work. Initializers work only with things you can directly assign like that. This is because events need to be able to notify anyone they want (you shouldn't be allowed to remove someone else's registration for that event on accident).

    I'm not sure if this is their reasoning, but it works for me.

提交回复
热议问题