Hierarchy structures
I have a requirement to represent a hierarchical structure in a class within开发者_StackOverflow中文版 c#. The "leaf" nodes of the hierarchy need to be typed as either "Class A" or "Class B".
How do I achieve this.
Ok more detail
The classes involved are as follows
FieldClass - this has a bunch of properties
SegmentClass - a segment is a collection of fields
GroupClass - a group is a collection of segments or groups (ie there is a recursive relationship)
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.
Make "ClassA" and "ClassB" implement a specific, shared interface (ie: ILeafNode
). You can then make your leaves ILeafNode
and add either class type to the tree.
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:
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. 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.
Hope that helps and good luck.
精彩评论