编译时间树结构

本文关键字:结构 时间 编译 | 更新日期: 2023-09-27 17:58:48

我想从存储在另一个系统中的树中检索值。例如:

GetValue("Vehicle.Car.Ford.Focus.Engine.Oil.Color")

为了避免键入错误和无效键,我想在编译时通过创建一个具有树结构的对象或类来检查名称:

GetValue(Vehicle.Car.Ford.Focus.Engine.Oil.Color)

在C#中有没有一种简单的方法可以做到这一点,而无需为每个树节点创建类?我可以使用匿名类或子类吗?我应该自动创建代码吗?

编译时间树结构

如果您想要进行编译时检查,您需要以某种方式使用编译时构造来定义您的结构。您可以使用T4文本模板从树结构中自动生成代码。

我能想到的可能方法:

嵌套的静态类

public static class Vehicle
{
    public static class Car
    {
        public static class Ford
        {
            public static class Focus
            {
                public static class Engine
                {
                    public static class Oil
                    {
                        public static readonly string Color =
                            "Vehicle.Car.Ford.Focus.Engine.Oil.Color";
                    }
                }
            }
        }
    }
}

命名空间和静态类

namespace Vehicle.Car.Ford.Focus.Engine
{
    public static class Oil
    {
         public static readonly string Color =
             "Vehicle.Car.Ford.Focus.Engine.Oil.Color";
    }
}

(请注意,不能在命名空间Vehicle.Car中同时具有类Ford和命名空间Vehicle.Car.Ford中的类。)

  • 如果不为每个树节点创建类,就无法做到这一点
  • 匿名类型和/或子类在这里没有帮助(至少我看不出怎么做)
  • 您可以自动生成类,您需要为其编写代码生成器,或者使用现有的代码生成器,如t4或CodeSmith。即使使用现有的代码生成器,您仍然需要编写一些代码来告诉它如何生成您的类

试试这样的东西:

var Vehicle = new { Car = new { Ford = new { Focus = new { Engine = new { Oil = new {Color = "Red"}}}}}};

现在,您可以使用intelligence获取每个值。

尽管我更喜欢@dtb方法。尽管如此,我认为我的方法很轻。

您可能可以找到一种使用C#扩展方法的方法:http://msdn.microsoft.com/en-us/library/bb383977.aspx

但可能无法摆脱某些自动代码生成