Add to a readonly collection in a constructor?

后端 未结 4 1887
醉梦人生
醉梦人生 2021-01-24 05:04

Is there a c# language construct that will allow me to add items to a readonly collection property in a constructor? I want to do something like this:

public cl         


        
4条回答
  •  醉梦人生
    2021-01-24 05:26

    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 _Children;
                public IList Children { get { return _Children; } }
                public Node(IList children)
                {
                    _Children = children;
                }
            }
    

    Then you can do this

    var node = new Node((new ObservableList()).Add(new Node()));
    

提交回复
热议问题