Automatically set parent link for child elements

I have a class that contains a property IList<T>called Children. Each child must refer to its parent. My solution was to set the property ChildClass.Parentto a getter ParentClass.Children. Is there a better way, or is this a better solution?

class ParentClass
{
    private IList<ChildClass> _children;

    public virtual IList<ChildClass> Children
    {
        get
        {
            // make sure each child refers to its parent (this)
            foreach (ChildClass c in _children)
            {
                c.Parent = c.Parent ?? this;
            }
            return _children;
        }
        set
        {
            _children = value;
        }
    }
}
+3
source share
2 answers

It may be just me ... but it looks like a bad design.

If this is the true Parent → Child relationship, you should not allow anyone to create an orphan. Therefore, the parent must be installed on the child at the time of creation.

I would probably do something like:

class ChildClass
{
    private ParentClass _parent;

    public ChildClass(ParentClass parent)
    {
        _parent = parent;
    }
}

And then:

class ParentClass
{
    private List<ChildClass> _children;

    public virtual ReadOnlyCollection<ChildClass> Children
    {
        get
        {
            return _children.AsReadOnly();
        }
    }

    public virtual ChildClass CreateChild()
    {
        // Set parent in child class constructor
        ChildClass newChild = new ChildClass(this);

        _children.Add(newChild);

        return newChild;
    }
}
+8
source

, , , ​​ . , , , , .

:

Add(ChildCLass) Remove(ChildClass) ParentClass parent-child. . , .

ChildClass, . ReadOnlyCollection IEnumerable.

:

class ChildClass
{
    // Prevent unauthorized clients from overriding the Parent reference.
    public ParentClass Parent { get; internal set; }

    // ... other methods and properties ...
}

class ParentClass
{
    private IList<ChildClass> _children;

    public void AddChild(ChildClass child)
    {
        _children.Add(child);
        child.Parent = this;
    }

    public RemoveChild(ChildClass child)
    {
        _children.Remove(child);
        child.Parent = null;
    }

    public IList<ChildClass> Children
    {
        get { return _children.AsReadOnly(); }
    }
}
0

Source: https://habr.com/ru/post/1732044/


All Articles