编译时树结构
我想从存储在另一个系统中的树中检索值。例如:
GetValue("Vehicle.Car.Ford.Focus.Engine.Oil.Color")
为了避免键入错误和无效键,我想通过创建一个包含树结构的对象或类来在编译时检查名称:
GetValue(Vehicle.Car.Ford.Focus.Engine.Oil.Color)
Is there a simple way to do this in C# without opening class for every tree node ?我可以使用匿名类或子类吗?我应该自动创建代码吗?
I want to retrieve values from a tree stored in another system. For example:
GetValue("Vehicle.Car.Ford.Focus.Engine.Oil.Color")
To avoid typing errors and invalid keys, I want to check the name at compile time by creating an object or class with the 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 tree node? Can I use anonymous classes or subclasses? Should I create the code automatically?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
如果您想要编译时检查,则需要以某种方式使用编译时构造来定义结构。您可以使用 T4 文本模板 从树结构自动生成代码。
我能想到的可能方法:
嵌套静态类
命名空间和静态类
(请注意,命名空间中不能同时拥有类
Ford
< code>Vehicle.Car 和命名空间Vehicle.Car.Ford
中的类。)If you want compile-time checking, you need to define your structure using compile-time constructs in some way. You could use T4 text template to automatically generate code from the tree structure.
Possible ways I can think of:
Nested static classes
Namespaces and static classes
(Note that you can't have both a class
Ford
in namespaceVehicle.Car
and classes in a namespaceVehicle.Car.Ford
.)尝试这样的事情:
现在您可以智能地获取每个值。
虽然我更喜欢@dtb 方法。不过我认为我的方法是相当轻量级的。
Try some thing like this:
Now you can get each value with intellisence.
Although I prefer @dtb approach. Still I think my approach is quite light weight.
您可能可以找到一种使用 C# 扩展方法来完成此操作的方法:http://msdn .microsoft.com/en-us/library/bb383977.aspx
但是可能无法避免某些自动代码生成
You can probably find a way to do it with C# Extension methods: http://msdn.microsoft.com/en-us/library/bb383977.aspx
But there's probably no escape from some automatic code generation