Enforcing parent-child relationship in C# and .Net

后端 未结 5 675
夕颜
夕颜 2020-12-14 23:29

Let\'s take the following two classes:

public class CollectionOfChildren
{
    public Child this[int index] { get; }
    public void Add(Child c);
}

public          


        
5条回答
  •  既然无缘
    2020-12-15 00:08

    I was also looking into it recently, and thought about really enforcing this relationship as error proof as possible. Additionally, I tried to keep it as general and type safe as possible. It may be just overengineered, but still I would like to share it.

    public class ChildCollection : IEnumerable 
        where TChild : ChildCollection.Child
    {
        private readonly List childCollection = new List();
    
        private void Add(TChild child) => this.childCollection.Add(child);
    
        public IEnumerator GetEnumerator() => this.childCollection.GetEnumerator();
    
        IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
    
        public abstract class Child
        {
            private readonly ChildCollection childCollection;
    
            protected Child(ChildCollection childCollection)
            {
                this.childCollection = childCollection;
                childCollection.Add((TChild)this);
            }
        }
    }
    

    Here comes the Example:

    public class Parent
    {
        public ChildCollection ChildCollection { get; }
        public Parent()
        {
            ChildCollection = new ChildCollection();
        }
    }
    
    public class Child : ChildCollection.Child
    {
       public Child(ChildCollection childCollection) : base(childCollection)
       {
       }
    }
    

    And adding a child to the parent would look like:

    var parent = new Parent();
    var child1 = new Child(parent.ChildCollection);
    

    The final implementation also has Ids for the children and allows removing of children. But the latter destroys the strong enforcement of the parent child relationship.

提交回复
热议问题