Add to a readonly collection in a constructor?

送分小仙女□ 提交于 2019-12-02 05:33:07

Try this. It is definitely possible to add elements on construction

var node = new Node
 {
     Children =
    {
        new Node(),
        new Node()
    }
 };

If you have a property of type List that is get only, that only means you can't set that property, you can still add things to the list.

You could however expose an IEnumerable property instead and have a constructor that takes a list(or another IEnumerable more likely).

Property initializers do not work since the compiler will just rewrite them to regular property assignments.

I'd do this:

public class Node{
    public IEnumerable<Node> Children {get; private set;}
    public Node(IEnumerable<Node> children){
        Children = children.ToList();
    }
}

if you can't change the Node class, I suggest writing a helper class similar to this:

public static Node Create(IEnumerable<Node> children)
{
    var n = new Node();
    foreach (var c in children)
        n.Children.Add(c);
     return n;
}

To use the collection initializer syntax from you second code snippet your Node class must implement IEnumerable and have a public method with the signature

void Add(Node child)

Hence such a class cannot offer the immutability you desire. I think the best solution to your problem would be to do this

public class Node
{
  public readonly IEnumerable<Node> Children;

  public Node(IEnumerable<Node> children)
  {
    Children = children;
  }
}

or if you do not like the deferred execution of IEnumerable:

public class Node
{
  public readonly ReadOnlyCollection<Node> Children;

  public Node(IEnumerable<Node> children)
  {
    Children = new ReadOnlyCollection<Node>(children);
  }
}

You can add a backing field to the "Children" property, then just populate the backing field during construction.

Like so

public class Node
        {
            private IList<Node> _Children;
            public IList<Node> Children { get { return _Children; } }
            public Node(IList<Node> children)
            {
                _Children = children;
            }
        }

Then you can do this

var node = new Node((new ObservableList<Node>()).Add(new Node()));
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!