[英]What's the best way to provide localization for Enums?
I'm writting a multi-lingual application that uses many enums, and I'd like to achieve the following objectives: 我正在编写一个使用很多枚举的多语言应用程序,我希望实现以下目标:
I'm keen to to decorate the enum using attributes + a resource file, such that the localized strings can be reached from run-time type info. 我热衷于使用属性+资源文件来修饰枚举,以便可以从运行时类型信息中获取本地化字符串。 I've been down the route before of declaring a static class with static members instead of an enum, but this presented as many problems as it solved.
在使用静态成员而不是枚举声明静态类之前,我一直沿着这条路走下去,但是这解决了很多问题。
Is some sort of a TypeDescriptor based mechanism appropriate? 某种基于TypeDescriptor的机制是否合适? Or even possible?
甚至可能吗?
Moreover - how does one accomplish goal #3 in a clean, generic, re-usable manner? 此外 - 如何以干净,通用,可重复使用的方式完成目标#3?
Since asking this question, I've completed the open source library that needed localizable enum displays. 自从提出这个问题以来,我已经完成了需要可本地化的枚举显示的开源库。 I went with the technique of implementing TypeConverters.
我选择了实现TypeConverters的技术。 Full source available at http://measures.codeplex.com/
完整资料来源于http://measures.codeplex.com/
How about writing TypeConvertor for your enums? 如何为你的枚举编写TypeConvertor ?
Parse<T>(string value)
where T will be enum type. Parse<T>(string value)
,其中T将是枚举类型。 The implementation will build (on demand) a lookup dictionary for given enum type T using reflection to look up for your custom attribute. I think you are in the exactly right direction — use attributes to decorate the enumeration members. 我认为你的方向正确 - 使用属性来装饰枚举成员。 The only think you probably need to do is forget about
System.ComponentModel
and design your own set of attributes that will respect your requirements and overall application architecture. 您可能需要做的唯一想法是忘记
System.ComponentModel
并设计您自己的一组属性,这些属性将尊重您的需求和整体应用程序架构。
We used the same approach and it works as expected “in a clean, generic, re-usable manner”. 我们使用相同的方法,它以“干净,通用,可重复使用的方式”按预期工作。 The only aspect we didn't implemented because we didn't need it was actual internationalization.
我们没有实施的唯一方面是因为我们不需要实际国际化。 However, that's just some mechanics that requires you to keep track of the current culture and decide where to select resource files.
但是,这只是一些需要您跟踪当前文化并决定在何处选择资源文件的机制。 Basically, you might need to select between “multiple attributes” (one per language) or “single attribute” (one for all languages encapsulating resource file selection) approach.
基本上,您可能需要在“多个属性”(每种语言一个)或“单个属性”(一个用于封装资源文件选择的所有语言)方法之间进行选择。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.