c# - 在 c# 中填充树结构的优雅且可维护的方式

标签 c# design-guidelines

我有一棵树。

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 .

implementation is 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/

相关文章:

c# - Azure/AWS ORM 设计指南

c# - 可以将委托(delegate)分配给匿名方法或 lambda,但不能分配给方法

c# - 复杂(多架构) Entity Framework 对象映射,用于办公室管理应用程序的无缝集成(并最终替换)

android - 如何禁用 Android Lollipop 波纹的 alpha 值?

user-interface - 隐藏还是禁用?在这个例子中以及一般情况下

ios - 我可以将整个 iOS 应用程序打包为一个框架吗?

c# - core 2.0 和 office interop - microsoft.office.core 包在哪里?

c# - 在 Pdf 上绘制成窗口窗体 C# (visual studio 2015)

c# - 在关闭事件中更改另一个表单文本