Initializing events with initializer syntax

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

    Yep, should be part of the language!

    But, here's a tricky workaround that lets you subscribe to events within an initializer list...

    public class TestClass
    {
        public class MyButton : Button
        {
            public EventHandler ClickSubscriber
            {
                get { return null; }
                set { Click += value; }
            }
        }
    
        public static void RunTest()
        {
            new Form
                {
                    Text = "Caption",
    
                    Controls =
                        {
                            new MyButton 
                                { 
                                    ClickSubscriber = (s, e) => 
                                         MessageBox.Show("Button 1 Clicked"), 
                                },
                        },
                };
        }        
    }
    

提交回复
热议问题