Compile-time tree structure

I want to get values ​​from a tree stored in another system. For instance:

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

To avoid entering errors and invalid keys, I want to check the name at compile time by creating an object or class with a tree structure in it:

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

Is there an easy way to do this in C # without creating classes for each node tree? Can I use anonymous classes or subclasses? Should I automatically generate code?

+5
source share
4 answers

, - . 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";
    }
}

( , Ford Vehicle.Car, Vehicle.Car.Ford.)

+4
+1

Try the following:

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

Now you can get each value with intellisence.

Although I prefer the @dtb approach. However, I think my approach is pretty easy.

+1
source

You might find a way to do this using the C # extension methods: http://msdn.microsoft.com/en-us/library/bb383977.aspx

But there is probably no way out of any automatic code generation

0
source

All Articles