创建数据层次结构并传递

时间:2014-01-04 15:36:23

标签: c# hierarchy

我正在尝试构建数据层次结构,我有以下代码:

public class TreeData
{
    public string parent { get; set; }
    public string child { get; set; }
    public List<TreeData> thisTree { get; set; }

    public void Add(string parent, string child)
    {
        this.parent = parent;
        this.child = child;
    }

    public void Add(List<TreeData> myList)
    {
        this.thisTree = myList;
    }

}

我也有这个用它:

TreeData myTree = new TreeData();
myTree.Add("Alan", "Dan");

TreeData myTree1 = new TreeData();
myTree1.Add("Dan", "Heidi");
myTree1.Add(myTree);

但是我无法将myTree传递给我的Add方法,因为它不是List,我需要做些什么才能将myTree传递回来我的班级?

谢谢, 丹

3 个答案:

答案 0 :(得分:1)

对于树状类,我建议使用以下结构:

public class TreeData
{
    public TreeData Parent { get; private set; }
    public string ID { get; private set; }
    public List<TreeData> Child { get; private set; }

    //Constructor for root objects
    public TreeData(string id) : this(null, id)
    {
    }

    //Constructor for child objects
    public TreeData(TreeData parent, string id)
    {
        this.ID = id;
        this.Parent = parent;
        this.Child = new List<TreeData>();
    }

    public TreeData Add(string childID)
    {
        TreeData child = new TreeData(this, childID);
        this.Child.Add(child);
        return child;
    }

}

这样每个节点都可以访问父节点和子节点

TreeData alanNode = new TreeData("Alan");
TreeData danNode = alanNode.Add("Dan");
danNode.Add("Heidi");

答案 1 :(得分:0)

为什么不更改

的签名
public void Add(string parent, string child)

public void Add(TreeData parent, TreeData child)

答案 2 :(得分:0)

我想你需要做的就是这样:

public class TreeData
{
    private TreeData _child;

    public string Name { get; set; }
    public TreeData Next
    {
        get { return _child; }
        set { _child = value; }
    }
}


TreeData myTree = new TreeData("root");
TreeData child1 = new TreeData("child1");
TreeData child2 = new TreeData("child2");
myTree.Next = child1;
child1.Next = child2;

如果您希望一个TreeData可能有多个子项,您可以像这样扩展此类:

public class TreeData
{
    private TreeData _parent;
    private List<TreeData> childs = new List<TreeData>(); 
    public TreeData(string name)
    {
        Name = name;
    }

    public void AddChild(TreeData child)
    {
        child.Parent = this;
        childs.Add(child);
    }

    public string Name { get; set; }
    public TreeData Parent
    {
        get { return _parent; }
        set { _parent = value; }
    }


    public List<TreeData> Childs
    {
        get { return childs; }
    } 
}

然后:

TreeData myTree = new TreeData("root);
TreeData child1 = new TreeData("child1");
TreeData child2 = new TreeData("child2");

myTree.AddChild(child1);
myTree.AddChild(child2);