Possible to mix object initializer and collection initializer?

后端 未结 5 1720
猫巷女王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:39

    I don't recommend in this case, but it's possible to use multiple Add overloads.

    So in ArrangedPannel include

    public void Add(int padding)
    {
        Padding = padding;
    }
    

    Then can defined in code like

    debugPanel.Add(new ArrangedPanel() 
    { 
        5, // is this Padding?
        new ButtonToggle(),
        new ButtonToggle()
    });
    

    But I prefer @Haymo's answer because here it's not clear what '5' is set to, and multiple int properties will probably lead to crazy code like

    public void Add(int intProp)
    {
        var current = intPropSetCount++;
        switch(current)
        {
            case 0: Padding = intProp; return;
            case 1: SecondProp = intProp; return;
            // ...
            default: throw new Exception();
        }
    }
    

    This idea is probably best left for combining multiple collections into 1 wrapper.

提交回复
热议问题