【发布时间】:2011-02-23 16:23:17
【问题描述】:
我在这里看到了很多关于我的问题的文章,但没有一个真正回答我的问题。我正在创建一个 Branch 对象类,您可以将其设想为就像 TreeView 控件的 TreeNode 对象一样。每个分支可以在其下方(因此在上方)有任意数量的分支子级。这是我相当简单的课程:
public class Branch {
public string Name { get; set; }
public string Link { get; set; }
public Branch Parent { get; private set; }
public List<Branch> Children { get; set; }
internal Branch(string Name, string Link) {
this.Name = Name;
this.Link = Link;
this.Children = new List<Branch>();
} // Branch - Constructor - Overload
internal Branch(string Name, string Link, List<Branch> Children) {
this.Name = Name;
this.Link = Link;
this.Children = Children;
this.Children.ForEach(delegate(Branch branch) {
branch.Parent = this;
});
} // Branch - Constructor - Overload
public bool HasChildren {
get { return this.Children.Count > 0; }
} // HasChildren - Property - ReadOnly
public string Path {
get {
string Result = "";
Branch parent = this;
while (parent != null) {
Result = string.Format("{0}/{1}", parent.Name, Result);
parent = parent.Parent;
} // while stepping up the tree
return string.IsNullOrWhiteSpace(Result) ? "" : Result.Substring(0, Result.Length - 1);
} // get
} // Path - Property - ReadOnly
如果我像下面这样在实例化时添加子项,这将非常有用:
List<Branch> Branches = new List<Branch>() {
new Branch("First", "#"),
new Branch("Second", "#"),
new Branch("Third", "#", new List<Branch>() {
new Branch("ThirdSub1", "#"),
new Branch("ThirdSub2", "#")
}),
new Branch("Fourth", "#"),
new Branch("Fifth", "#"),
new Branch("Sixth", "#", new List<Branch>() {
new Branch("SixthSub1", "#"),
new Branch("SixthSub2", "#", new List<Branch>() {
new Branch("SixthSub2Sub1", "#"),
new Branch("SixthSub2Sub2", "#"),
new Branch("SixthSub2Sub3", "#", new List<Branch>() {
new Branch("Deep Deep Deep Undercover", "#"),
}),
}),
}),
new Branch("Seventh", "#"),
new Branch("Eighth", "#"),
};
但如果我执行以下操作:
List<Branch> Branches = new List<Branch>();
Branch Test = Branches.Add(new Branch("Something", ""));
Test.Children.Add(new Branch("Child Here", ""));
“Child Here”节点没有与之关联的 Parent。因此它被破坏了,当然 Path 属性不起作用。
我以为我可以覆盖 List 的 Add 方法,但这是不允许的。处理这个问题的最佳方法是什么?目前我没有创建我自己的 Collection 类,比如我喜欢的 MyBranches,但是如果有一种方法可以在实现 IList 或 ISet 或 Collection 时做我需要的事情,那么我愿意这样做。但请举个例子。
谢谢!
【问题讨论】:
-
为您的分支类型尝试扩展方法。这是一种添加重载的方法。也就是说,如果您的类型继承自 IList。不幸的是,您将无法访问受保护或私人成员。
标签: c# generics collections hierarchy