Add to a readonly collection in a constructor?

后端 未结 4 1892
醉梦人生
醉梦人生 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: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 Children;
    
      public Node(IEnumerable children)
      {
        Children = children;
      }
    }
    

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

    public class Node
    {
      public readonly ReadOnlyCollection Children;
    
      public Node(IEnumerable children)
      {
        Children = new ReadOnlyCollection(children);
      }
    }
    

提交回复
热议问题