为枚举提供本地化的最佳方式是什么? [英] What's the best way to provide localization for Enums?

查看:161
本文介绍了为枚举提供本地化的最佳方式是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在写一个使用许多枚举的多语言应用程序,我想实现以下目标:


  1. 显示枚举名称作为本地化字符串

  2. 使用属性提供本地化描述

  3. 启用语言敏感的枚举枚举回到int值

我很想使用属性+资源文件装饰枚举,以便可以从运行时类型信息到达本地化的字符串。我已经在路由之前宣布一个静态成员而不是一个枚举的静态类,但这表明了许多问题,解决了。



是否适合基于TypeDescriptor的某种机制?或者甚至可能?



此外 - 以干净,通用,可重复使用的方式完成目标3?






由于提出这个问题,我已经完成了需要可本地化枚举显示的开源库。我去了实现TypeConverters的技术。完整来源可以在 http://measures.codeplex.com/ 获得

解决方案

如何写


  1. 定义一些自定义属性,用于标识枚举值的资源字符串。

  2. 编写TypeConvertor,将查找此属性以获取资源ID,然后将该值转换为字符串。 (你可以使用类Helper类,但是使用TypeConvertor和TypeConvertorAttribute可以更透明地使用它)。

  3. 你可以编写一个通用的类/方法来进行逆转换(从字符串到枚举)。该方法将类似于 Parse< T>(string value),其中T将是枚举类型。实现将使用反射来构建(按需)用于给定枚举类型T的查找字典,以查找您的自定义属性。


I'm writting a multi-lingual application that uses many enums, and I'd like to achieve the following objectives:

  1. Display Enum names as localized strings
  2. Provide localized descriptions using attributes
  3. Enable language sensitive parsing of enums back to int values

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? Or even possible?

Moreover - how does one accomplish goal #3 in a clean, generic, re-usable manner?


Since asking this question, I've completed the open source library that needed localizable enum displays. I went with the technique of implementing TypeConverters. Full source available at http://measures.codeplex.com/

解决方案

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.

这篇关于为枚举提供本地化的最佳方式是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆