Skip to main content
 首页 » 编程设计

c#之如何创建树状结构

2024年02月20日15wuhuacong

我想创建如下数据结构。

对于这个,我想使用键值对结构。但我无法创建它。

public class NewStructure 
{ 
    public Dictionary<string, Dictionary<string, bool>> exportDict; 
} 

这是正确的方法吗?如果是这样,我如何向它插入值。如果我插入

NewStructure ns = new NewStructure(); 
ns.exportDict.Add("mainvar",Dictionary<"subvar",true>); 

它给出了编译错误。 我什么也没想到。请有任何建议。

请您参考如下方法:

您可以通过以下方式消除错误

Dictionary<string, bool> values = new Dictionary<string, bool> (); 
values.Add("subvar", true); 
ns.exportDict.Add("mainvar", values); 

但也许你最好尝试这样的事情:

class MyLeaf 
{ 
  public string LeafName {get; set;} 
  public bool LeafValue {get; set;} 
} 
class MyTree 
{ 
  public string TreeName {get; set;} 
  public List<MyLeaf> Leafs = new List<MyLeaf>(); 
} 

然后

MyTree myTree = new MyTree(); 
myTree.TreeName = "mainvar"; 
myTree.Leafs.Add(new MyLeaf() {LeafName = "subvar", LeafValue = true});