2013-12-22 92 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; } 
}