在C#和.NET执行亲子关系 [英] Enforcing parent-child relationship in C# and .Net
问题描述
让我们采取以下两类:
公共类CollectionOfChildren
{
公共儿童这个[ INT指数] {搞定; }
公共无效添加(Child C级);
}
公共类儿童
{
公共CollectionOfChildren家长{搞定; }
}
孩子的父母属性应始终返回CollectionOfChildren孩子在,或如果孩子是空没有这样一个收藏。这两个类之间,不变的应该由类的使用者进行维护,而不应该是易碎的(当然,很容易)。
如何实现这样的关系? CollectionOfChildren不能设置任何儿童的私有成员,因此它应该如何告诉孩子,这是添加到集合?
(抛出异常是可以接受的,如果孩子已经是一个集合的一部分。)
的
内部
关键字已经被提及。我写的那一刻WinForms应用程序,所以一切都是在同一个程序集,这基本上是不超过公共
。
公共类CollectionOfChildren
{
公共儿童这个[INT指数] {搞定; }
公共无效添加(Child C级){
c.Parent =这一点;
innerCollection.Add(三);
}
}
公共类儿童
{
公共CollectionOfChildren家长{搞定;内部设置; }
}
Let's take the following two classes:
public class CollectionOfChildren
{
public Child this[int index] { get; }
public void Add(Child c);
}
public class Child
{
public CollectionOfChildren Parent { get; }
}
Child's Parent property should always return the CollectionOfChildren that the Child is in, or null if the child is not in such a collection. Between these two classes, this invariant should be maintained, and should not be breakable (well, easily) by the consumer of the class.
How do you implement such a relationship? CollectionOfChildren cannot set any of the private members of Child, so how is it supposed to inform Child that it was added to the collection? (Throwing an exception is acceptable if the child is already part of a collection.)
The internal
keyword has been mentioned. I am writing a WinForms app at the moment, so everything is in the same assembly, and this is essentially no different than public
.
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; }
}
这篇关于在C#和.NET执行亲子关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!