加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

在C#和.Net中实施父子关系

发布时间:2020-12-15 04:24:13 所属栏目:百科 来源:网络整理
导读:我们来看以下两个类: public class CollectionOfChildren{ public Child this[int index] { get; } public void Add(Child c);}public class Child{ public CollectionOfChildren Parent { get; }} Child的Parent属性应始终返回Child所在的CollectionOfChil
我们来看以下两个类:
public class CollectionOfChildren
{
    public Child this[int index] { get; }
    public void Add(Child c);
}

public class Child
{
    public CollectionOfChildren Parent { get; }
}

Child的Parent属性应始终返回Child所在的CollectionOfChildren,如果子节点不在此类集合中,则返回null.在这两个类之间,应该保持这个不变量,并且不应该被类的消费者破坏(很好,很容易).

你是如何实现这种关系的? CollectionOfChildren不能设置Child的任何私有成员,那么它应该如何通知Child它已被添加到集合中?
(如果孩子已经是一个集合的一部分,则抛出异常是可以接受的.)

已提及内部关键字.我现在正在编写一个WinForms应用程序,所以一切都在同一个程序集中,这与公众基本没什么不同.

解决方法

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

public class Child
{
    public CollectionOfChildren Parent { get; internal set; }
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读