本地化枚举描述属性
在 .net 中本地化枚举描述的最佳方法是什么?
(有关枚举描述示例,请参阅向枚举常量添加描述)
理想情况下,我想要使用 ResourceManager 和资源文件的东西,以便它适合应用程序其他区域的本地化方式。
What is the best way to localize enumeration descriptions in .net?
(See Adding descriptions to enumeration constants for enum description example)
Ideally I would like something that uses ResourceManager and resource files so it fits in with how other areas of the app are localized.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(9)
这就是我最终的结果,我没有看到添加自定义属性类来保存资源键然后查找资源文件的价值 - 为什么不只使用枚举类型名+值作为资源键?
This is what I ended up going with, I didn't see the value in adding a custom attribute class to hold a resource key and then looking up into the resource files - why not just use the enums typename + value as a resource key?
我的解决方案,使用本机描述属性:
Enum 声明
然后调用 MyEnumInstance.GetLocalizedDescription()
My solution, using native decription attribute:
The Enum declaration
Then call
MyEnumInstance.GetLocalizedDescription()
有一个简单的解决方案:
使用 LocalizedDescription 属性来传递资源密钥。
there is an easy solution:
use LocalizedDescription attribute to pass a resource key.
我曾经做过的一种方法是在与枚举相同的命名空间中添加扩展方法,该方法返回一个字符串。 就我而言,它只是硬编码,但从资源文件中获取它们是没有问题的。
也许不是一个极其顺利或奇特的解决方案,但它有效 =)
One way I did it once, was to add an extention method in the same namespace as an enum, which returned a string. In my case it was just hardcoded, but would be no problem getting them from a resource file.
Maybe not an extremly smooth or fancy solution, but it works =)
将 @nairik 的方法替换为以下内容以添加对标志枚举的支持。
并替换属性中的NameResourceType:
Replace @nairik's method with the following to add support for flags enums.
and replace NameResourceType in the attribute:
请参阅此问题中的表示例:
数据库数据的本地化/I18n在 LINQ to SQL 中,
状态类型表映射到枚举值。 这里真正的好处是,您可以在报告和跨应用程序中进行本地化,并指定外部 ID 以便与不需要您的内部值等的第三方集成。它将枚举描述与其值分离。
See my table example in this question:
Localisation/I18n of database data in LINQ to SQL
The status type table maps to Enumeration values. The real benefit here is that you can have localisation in your reports and across your applications, and specify external IDs for integration with 3rd parties who don't want your internal values etc. It decouples the enum description from it's value.
您不能应用多个 System.ComponentModel.DescriptionAttribute(因此该选项已失效)。
因此添加一个间接级别,描述保存资源名称,然后使用资源中的本地化支持。 显然,枚举的用户需要调用您的辅助方法来执行此操作。
You can't have multiple System.ComponentModel.DescriptionAttribute applied (so that option is out).
So add a level of indirection, the description holds a resource name, and then use the localisation support in resources. Clearly users of the enum will need to call your helper method to do this.
我的解决方案受到nairik的答案的启发,是使用现有的
DisplayAttribute
:属性用法:
My solution, inspired by nairik's answer, is to use the already existing
DisplayAttribute
:Attribute usage:
这看起来不错: http://www.codeproject.com /Articles/19980/带描述的数据绑定枚举
This looks good: http://www.codeproject.com/Articles/19980/Data-Binding-an-Enum-with-Descriptions