Add to a readonly collection in a constructor?

后端 未结 4 1886
醉梦人生
醉梦人生 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<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()));
    
    0 讨论(0)
  • 2021-01-24 05:29

    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;
    }
    
    0 讨论(0)
  • 2021-01-24 05:37

    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);
      }
    }
    
    0 讨论(0)
  • 2021-01-24 05:39

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

    var node = new Node
     {
         Children =
        {
            new Node(),
            new Node()
        }
     };
    
    0 讨论(0)
提交回复
热议问题