What is the best way to provide localization of Enums?

I am writing a multilingual application that uses many enumerations, and I would like to achieve the following goals:

  • Display Enum names as localized strings
  • Providing localized descriptions using attributes
  • Enabling language analysis of parsing enumerations back into int values

I try to decorate enum using attributes + a resource file, so that localized strings can be obtained from information such as runtime. I used to be on the way to declaring a static class with static members, not an enumeration, but this represented as many problems as possible.

Is some typeDescriptor based mechanism suitable? Or is it even possible?

Moreover - how to achieve goal number 3 in a clean, general, reuse?




Asking this question, I ended up with an open source library that needed localized enum mappings. I went with the TypeConverters implementation technique. The full source is available at http://measures.codeplex.com/

+6
enums c # internationalization localization
Oct. 12 2018-10-12
source share
3 answers

How about writing TypeConvertor for your listings?

  • Define some custom attribute that will define the resource string for the enumeration value.
  • Write TypeConvertor, which will look for this attribute to get the resource identifier, and then convert the value to a string. (You may have a helper class for the same thing, but using TypeConvertor and TypeConvertorAttribute allows you to use it more transparently).
  • You can write a generic class / method that will perform the inverse transform (from string to enumeration). This method will look like Parse<T>(string value) , where T will be an enum type. The implementation will build (on demand) a search dictionary for this type of enumeration T using reflection to search for your custom attribute.
+5
Oct 12 2018-10-12
source share

I just wrote an answer to another thread regarding some things. Look here for some sample code.

+4
Oct 12 2018-10-12
source share

I think you're in the right direction - use attributes to decorate enumeration elements. The only thing you probably need to do is forget about System.ComponentModel and create your own set of attributes that will respect your requirements and the overall application architecture.

We used the same approach, and it works as expected, "in a clean, universal, reusable". The only aspect that we did not realize, because we did not need real internationalization. However, these are just some of the mechanics that require you to keep track of your current culture and decide where to select resource files. Basically, you may need to choose between “multiple attributes” (one per language) or “single attribute” (one for all languages ​​encapsulating the selection of a resource file).

+4
Oct 12 2018-10-12
source share



All Articles