2013-12-22 63 views
1

我有一个对象myBook。在c上实现树形结构#

我可以为这种数据实现更好的结构吗?

public class myRow{ 

    public int ID = 0; 
    public int number = 0; 
    public String param1 = null; 
    public decimal param2 = null; 
    public string parm3 = ""; 
    public int param4 = null; 

} 

public class mySubChapter{ 

    public int ID = 0; 
    public string title = ""; 
    public List<myRow> rows; 

    internal bool sort(){...} //sort rows by ID 
} 

public class myChapter{ 

    public int ID = 0; 
    public string title = ""; 
    public List<mySubChapter> subChapters; 

    internal bool sort(){...} //sort subChapters by ID 
} 

public class myBook{ 
    public int ID = 0; 
    public string title = "" 
    public List<myChapter> chapters; 

    internal bool sort(){...} //sort chapters by ID 
} 
+0

该数据结构的目的是什么?你想保留整本书的文本还是只保存图书馆目录中的信息? – PMF

+0

@PMF我将保存对象中的所有数据,我需要将其序列化并将其传输到另一个客户端。 – eyalb

回答

0

在我看来,我会合并小节和chapper类为一类myChaper并添加新特性是chapterLevel在里面。因为我认为subchapter也是一个章节,只是差异程度(章节的孩子可能)。对不起我的英语不好。

public class myRow{ 

    public int ID = 0; 
    public int number = 0; 
    public String param1 = null; 
    public decimal param2 = null; 
    public string parm3 = ""; 
    public int param4 = null; 

} 

public class myChapter{ 

    public int ID = 0; 
    public string title = ""; 
    public int chapterLevel = 0; 

    internal bool sort(){...} //sort chapters by ID and level 
} 

public class myBook{ 
    public int ID = 0; 
    public string title = "" 
    public List<myChapter> chapters; 

    internal bool sort(){...} //sort chapters by ID 
} 
2

如果你真的想你的书结构树模型,你可以使用一个通用的树实现像一个提出here

public interface INode 
{ 
    int Id { get; set; } 

    INode Parent { get; } 

    ReadOnlyCollection<INode> Children { get; } 

    void SetParent(INode node); 

    void AddChild(INode node); 
} 

public class Node : INode 
{ 
    private INode _parent; 

    private IList<INode> _children; 

    public Node() 
    { 
     _children = new List<INode>();  
    } 

    public int Id { get; set; } 

    public INode Parent 
    { 
     get { return _parent; } 
    } 

    public ReadOnlyCollection<INode> Children 
    { 
     get 
     { 
      return new ReadOnlyCollection<INode> 
         (_children.OrderBy(c => c.Id).ToList()); 
     } 
    } 

    public virtual void AddNode(INode node) 
    { 
     _children.Add(node); 

     node.SetParent(this); 
    } 

    public virtual void SetParent(INode node) 
    { 
     _parent = node; 
    } 
} 

的班,排,第三章,书可以从Node类,例如派生:那么,你可以使用这样的代码

DTreeNode<string> root = new DTreeNode<string>(); 
DTreeNode<string> temp; 

temp = root.Nodes.Add("Hello"); 
temp.Nodes.Add("olleH"); 

temp = root.Nodes.Add("World"); 
temp.Nodes.AddRange(new string[] 
     { "dWorl", "ldWor", "rldWo", "orldW" }); 
0

另一棵树的实现形式中一棵树

public class Book : Node 
{ 
    public override void SetParent(INode node) 
    { 
     throw new InvalidOperationException(); 
    } 

    public string Title { get; set; } 
}