2011-06-09 53 views
5

我想从存储在另一个系统中的树中检索值。例如:编译时间树结构

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

避免输入错误和无效的键,我想通过它创建一个对象或类树结构,以检查在编译时的名字:

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

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

+0

你可以(应该)自动创建代码 – sehe 2011-06-09 07:59:51

+0

你的意思是说,这就像一个类层次结构? – 2011-06-09 08:00:16

+0

是的,一个类层次结构。 Oil.Color可能是一个包含密钥的字符串。 – Sjoerd 2011-06-09 08:06:08

回答

4

如果你想编译时检查,你需要用某种方式使用编译时结构来定义你的结构。您可以使用T4 text template自动从树结构中生成代码。

我能想到的可能途径:

嵌套静态类

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和cl中的Ford类驴在命名空间Vehicle.Car.Ford

1
  • 你离不开每个创建类做到这一点树节点
  • 匿名类型和/或子类在这里没有帮助(至少我看不出)
  • 您可以自动生成类,您需要为它编写代码生成器,或者使用存在于例如t4CodeSmith。即使使用现有的代码生成器,您仍然需要编写一些代码来告诉它如何生成类。
1

尝试一些像这样的事情:

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

现在,你可以得到intellisence每个值。

虽然我更喜欢@dtb方法。不过,我认为我的方法非常轻。