4

我正在开发一个 CAD 应用程序,其中有块实体。每个块实体都有一个子实体列表。When these entities are rendered, every block entity knows about its child entity (as it can figure out the child entity in the list), and hence when block entity is selected, the whole block entity along with its child entities gets selected. However, child entity does not know the parent block and other child entities of that block, and due to this when child entity is selected, I cannot get the whole block entity along with all its child entities selected.

为了解决这个问题,我在子实体中创建了一个属性来保存父块实体的引用。但是,交叉引用可能会出现一些问题,并使我的数据结构容易出错。

例如:有一个复制命令,几天后处理这些数据结构的人可能会在创建子实体的副本时复制同一个父实体。但是,新副本应该属于某个其他父块。

请提出实现这种关系的更好方法,以便在选择子实体时,我可以选择整个块实体及其所有子实体。

public class BlockEntity
{
    public List<ChildEntity> Children = new List<ChildEntity>();
}

public class ChildEntity
{
    public readonly BlockEntity Parent;
}
4

2 回答 2

2

我最近遇到了这个问题。我和其他与我交谈的人提出了两个选择:

  1. Do what you are doing with the Parent<-->Child relationship, both knowing about each other.
  2. Have a Parent-->Child relationship and make everything be handled at the parent.

Both are viable solutions, but both have their issues. The first case, what you are doing, seems better and Microsoft seems to use this with their TreeView/TreeNode and DataTable/DataRow/etc. objects for example, because they can each reference back to their respective parents.

Maybe add constraints to the parent, such as not allowing access to the parent's child-collection directly, but only allowing an AddChild function in which you can do the necessary linking. Or do what @Irfan suggests and have the child require you pass the parent to its constructor. Constrain your copy method as well, but always document everything to remove as much confusion as possible.

The later of the above examples is a little easier as everything is always accessed from the parent. This was our solution. We have many functions in the parent to check for and manage the children within. So in this case you would select the child in the CAD app then go to the parents and check in their collection to see if the child exists there. If it does you select the parent and the rest of the children.

It's up to you, but in each case you need to add constraints and error checking to make sure things happen as close to your desired way as possible. Hope this helps.

于 2013-11-05T15:14:00.917 回答
1

通过创建对父级的引用,您会遇到哪些引用问题?有了这个只能在对象构造期间设置的只读引用,我觉得一点问题都没有。

构造函数(我相信你知道)看起来像:

public ChildEntity(BlockEntity p)
{
  Parent = p;
}
//Test just to show Parent can not be assigned elsewhere
public void test()
{
//this line below will show compile error
  Parent = new BlockEntity();
}

你觉得这样会不会有问题。该列表是一个松散的引用,因此没有堆栈溢出异常。

于 2013-11-05T15:01:37.603 回答