简体   繁体   English

层次结构

[英]Hierarchy structures

I have a requirement to represent a hierarchical structure in a class within c#. 我需要在c#中的类中表示层次结构。 The "leaf" nodes of the hierarchy need to be typed as either "Class A" or "Class B". 层次结构的“叶”节点需要键入为“ A类”或“ B类”。

How do I achieve this. 我该如何实现。

Ok more detail 确定更多细节

The classes involved are as follows 涉及的课程如下

FieldClass - this has a bunch of properties FieldClass-这有很多属性

SegmentClass - a segment is a collection of fields SegmentClass-段是字段的集合

GroupClass - a group is a collection of segments or groups (ie there is a recursive relationship) GroupClass-组是段或组的集合(即存在递归关系)

The nodes on the hierarchy can be either "segments" or "groups". 层次结构上的节点可以是“段”或“组”。 So at the root level this a collection where the classes can be either of type segment or group. 因此,在根级别上,这是一个集合,其中的类可以是segment类型或group类型。

Make "ClassA" and "ClassB" implement a specific, shared interface (ie: ILeafNode ). 使“ ClassA”和“ ClassB”实现一个特定的共享接口(即ILeafNode )。 You can then make your leaves ILeafNode and add either class type to the tree. 然后,您可以使叶ILeafNode离开,并将任一类类型添加到树中。

This represents your structure: 这表示您的结构:

interface IGroupNode
{ }

class Group : IGroupNode
{
    List<IGroupNode> Children { get; set; }
}

class Segment : IGroupNode
{
    List<Field> Fields { get; set; }
}

class Field
{
    bool myProperty { get; set; }
}

And the tree can be instantiated with a list of IGroupNodes: 并且可以使用IGroupNodes列表实例化该树:

var rootLevel = new List<IGroupNode>();

As there is not a lot of information on what your exact requirement is, I will give you two starting places to work from. 由于没有多少关于您的确切要求的信息,我将为您提供两个出发点。

One if you need to have a data structure of disparate child types, but that are still similar in typing look into using " interfaces " or " base classes " (in this case abstract classes). 如果您需要具有不同子类型的数据结构,但是在键入方面仍然相似,则可以使用“ 接口 ”或“ 基类 ”(在本例中为抽象类)。 "Class A" and "Class B" can both derive from "ISomeClass" or "SomeClassBase" and would still be similar in structure. “ A类”和“ B类”都可以派生自“ ISomeClass”或“ SomeClassBase”,并且在结构上仍然相似。 so that you can use a generic data structure such as List or Dictionary for them. 这样您就可以为它们使用通用的数据结构,例如列表或字典。

If you are wanting to visually display this list you can look into the TreeView Control or its equivalent in the SilverLight or ASP.NET spaces. 如果要直观地显示此列表,可以在SilverLight或ASP.NET空间中查看TreeView控件或其等效项。

Hope that helps and good luck. 希望对您有所帮助,并祝您好运。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM