Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
457 views
in Technique[技术] by (71.8m points)

c# - Possible to mix object initializer and collection initializer?

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 my collection initializer and they are added wih my Add() method like so:

class ArrangedPanel : RectElement
{
    private List<RectElement> arrangedChildren = new List<RectElement>();
    public int Padding = 2;

    public void Add(RectElement element)
    {
        arrangedChildren.Add(element);
        //do custom stuff here
    }

    public IEnumerator GetEnumerator()
    {
        return arrangedChildren.GetEnumerator();
    }
}

// Somewhere
debugPanel.Add(new ArrangedPanel() 
{ 
    new ButtonToggle(),
    new ButtonToggle()
});

However, if I try to set a property, such as my "Padding" field, I get an error on the collection initializers.

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

Is it possible to set both collection initializers and object initializers?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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<RectElement> 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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...