使用什么样的数据结构?
我正在开展一个需要跟踪的项目:
- 5-6只是字符串名称的根项
- 每个根项都需要具有不同标识符类型的多个子项(int,string,float等)。 一个根的所有子节点都是相同类型,但每个根节点将具有不同的子类型
- 用户需要能够从每个根添加/删除子项
- 我稍后需要单独访问每个孩子,并在需要时执行字符串操作和解析
我想过可能会使用一个字典,其中Key是一个字符串,而Values是对象列表。 或者每个根项都有一个唯一的类,每个类都包含一个子列表。
有没有人有任何好的建议? 我对OOP还很新,请耐心等我:)
谢谢!
public interface IRoot {} public class RootItem : IRoot { public string Name { get; set; } public List Children {get; set; } }
然后保持一个Dictionary
来保存它们。
Dictionary hair = new Dictionary(); hair.Add( new RootItem() { Name = "None", Children = new List () {1, 2, 3, 4} } ); hair.Add( new RootItem() { Name = "None", Children = new List () {1m, 2m, 3m, 4m} } );
如何使用List
包含子类的generics类:
public class Root { private List children = null; public Root(string name) { Name = name; } public string Name { get; set; } public List Children { get { if (children == null) { children = new List (); } return children; } } } Root intRoot = new Root ("IntRoot"); intRoot.Children.Add(23); intRoot.Children.Add(42); Root stringRoot = new Root ("StringRoot"); stringRoot.Children.Add("String1"); stringRoot.Children.Add("String2"); stringRoot.Children.Add("String3"); stringRoot.Children.Add("String4");
如果你想在一个对象中保存所有的根,你可以编写自己的类或使用一个Tuple
:
var rootGroup = Tuple.Create(intRoot, stringRoot); // intRoot is accessible as rootGroup.Item1 // stringRoot is accessible as rootGroup.Item2
听起来像Dictionary
是一个很好的候选者。
键是字符串(root)。 根的孩子是元组。 我们可以添加项目到元组。 感谢您指出了这一点。
元组的好起点
这是一种方法。 需要进行大量的投射,但它完成了工作:
static void Main(string[] args) { Dictionary values = new Dictionary(); values["strings"] = new RootCollection(); (values["strings"] as RootCollection ).Add("foo"); (values["strings"] as RootCollection ).Add("bar"); values["ints"] = new RootCollection(); (values["ints"] as RootCollection ).Add(45); (values["ints"] as RootCollection ).Add(86); } interface IRootCollection { } class RootCollection : List , IRootCollection { }