我有一棵树。
class TreeNode {
public TreeNode(string name, string description) {
Name = name;
Description = description;
}
string Name { get; set; }
string Description { get; set; }
public List<TreeNode> Children = new List<TreeNode>();
}
出于单元测试的目的,我想填充一个大的。我真的很想让东西保持干燥。
为了便于说明,我的树具有以下结构
Parent,desc Child 1, desc1 Grandchild 1, desc1 Child 2, desc2
How would you go about populating the tree in an elegant an maintainable way?
I find this code quite repetitious and error prone:
var parent = new TreeNode("Parent", "desc");
var child1 = new TreeNode("Child 1", "desc1");
var child2 = new TreeNode("Child 2", "desc2");
var grandchild1 = new TreeNode("Grandchild 1", "desc1");
parent.Children.Add(child1);
parent.Children.Add(child2);
child1.Children.Add(grandchild1);
编辑
我最终采用了 DSL 方法:
演示 test lives here .
它使用构建器和简单的 DSL。
最佳答案
你可以写一个带有状态的“TreeBuilder”来保存一些连接困惑:
TreeBuilder builder = new TreeBuilder();
builder.AddNode("Parent", "desc"); // Adds a node, and sets the cursor to it
builder.AddLeaf("Child 1", "desc1"); // Adds a node and leaves the cursor at the Parent
builder.AddNode("Child 2", "desc2");
builder.AddLeaf("Grandchild 1", "desc1");
builder.Up(); // Moves the cursor to the parent
builder.AddNode("Child 3", "desc3");
root = builder.GetRoot()
另一种方法是使用一些简单的格式发明一个简单的配置文件/字符串。
关于c# - 在 c# 中填充树结构的优雅且可维护的方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/563328/