Possible to mix object initializer and collection initializer?

后端 未结 5 1699
猫巷女王i
猫巷女王i 2020-12-18 21:46

I define an collection initializer with IEnumerable as instructed here: http://msdn.microsoft.com/en-us/library/bb384062.aspx

Now I\'m able to create objects within

5条回答
  •  离开以前
    2020-12-18 22:43

    I had a similar problem. The closest one can obviously get, is to add a property to the class which allows the collection initializer access:

    In ArrangedPanel:

    public ArrangedPanel Container {
       get { return this; }
    }
    

    And in code:

    debugPanel.Add(new ArrangedPanel() 
    { 
        Padding = 5,
        Container = {
            new ButtonToggle(),
            new ButtonToggle()
        }
    });
    

    not too bad, I guess ?

    @Edit: according to the comment by @Tseng I changed the return value of the new property to return the ArrangedObject itself instead of its List member. This way the ArrangedPanel.Add method is called and any (potentially more complex) logic in it is reused.

    @Edit2: renamed the property ('Children' -> 'Container') in the hope that the new name better reflects the new meaning.

提交回复
热议问题