填充树结构,在C#中的优雅和维护的方法 [英] Elegant and maintainable way of populating Tree structures in c#

查看:109
本文介绍了填充树结构,在C#中的优雅和维护的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一棵树。

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>();
}



我想填充一个大的单元测试的目的。我真的想保持东西干燥。

I would like to populate a large one for unit testing purposes. I would really like to keep stuff DRY.

假设为便于说明我的树结构如下

Say for illustration purposes my tree has the following structure


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的方式:

I ended up doing the DSL approach:

一个演示的测试住在这里

实施是这里

它使用一个建设者和简单的DSL。

It uses a builder and a simple DSL.

推荐答案


  • 在理想情况下,你想要的方式来扩展语言为自定义类型<的文字/ STRONG>。 C#不具备这一点,所以你必须要找到另一种方法。

  • Ideally you want a way to extend the language to literals of custom types. C# doesn't have this, so you have to find another approach.

    您可以编造一个内部DSL ,通常与流畅的界面

    You can fabricate an internal DSL, typically with a fluent interface.

    按照 <$ C $ 功能建设的C>的XElement 例如

    创建一个外部DSL 使用自定义解析器。如果你精心设计的语言,语法分析程序可以很容易。

    Create an external DSL with a custom parser. If you design the language carefully, the parser can be easy.

    使用 XML 。基本上,这是创建外部DSL和免费获得解析器的方法。

    Use XML. Basically this is a way to create an external DSL and get the parser for free.

    外部DSL选项是不错的,因为当你阅读他们,你知道有的唯一的数据,而不必担心使得代码结构感。此外,数据是文件,并且该文件中的数据。这使得它很容易通过改变文件交换左右的数据,也更容易准备的文件更改历史。最后,外部DSL是好当一个非程序员会提供的数据。

    The external DSL options are nice because when you read them, you know there's only data, and don't have to worry about making sense of code constructs. Also, the data is the file, and the file is the data. That makes it easy to swap data around by changing files, and easier to ready file change histories. Finally, and external DSL is good when a non-programmer will be supplying the data.

    的权衡这里是时间与价值。 你有多少数据/怎么会经常更改/谁将会改变它你必须回答的问题。

    The tradeoff here is time vs. value. How much data you will have / how often it will change / who will change it are the questions you have to answer.

    这篇关于填充树结构,在C#中的优雅和维护的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆