What's the best way to provide localization for Enums?

白昼怎懂夜的黑 提交于 2019-11-30 14:20:11

How about writing TypeConvertor for your enums?

  1. Define some custom attribute that will identify resource string for enum value.
  2. Write TypeConvertor that will look up this attribute to get resource id and then convert the value to string. (You can have helper class for the same but using TypeConvertor and TypeConvertorAttribute allows to use it more transparently).
  3. You can write a generic class/method that will do reverse conversion (from string to enum). The method will be something like Parse<T>(string value) where T will be enum type. The implementation will build (on demand) a lookup dictionary for given enum type T using reflection to look up for your custom attribute.
danijels

I just wrote an answer to another thread touching on some of the stuff. Look here for some code samples.

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.

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!