本地化枚举描述属性 [英] Localizing enum descriptions attributes
本文介绍了本地化枚举描述属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
(请参阅为枚举常量添加描述对于枚举描述示例)
理想情况下,我想使用ResourceManager和资源文件的东西,使其适合应用程序的其他区域本地化。
解决方案
这是我的结束了,我没有看到添加自定义属性类以保存资源密钥,然后查找资源文件的价值 - 为什么不使用枚举typename +值作为资源密钥?
using System;
使用System.Resources;
使用System.Reflection;
public class MyClass
{
enum SomeEnum {Small,Large};
private ResourceManager _resources = new ResourceManager(MyClass.myResources,
System.Reflection.Assembly.GetExecutingAssembly());
public string EnumDescription(枚举枚举器)
{
string rk = String.Format({0}。{1},enumerator.GetType(),枚举器);
string localizedDescription = _resources.GetString(rk);
if(localizedDescription == null)
{
//没有找到本地化的字符串,所以你可以只返回
//枚举值 - 最有可能可读性好回退。
return enumerator.ToString();
//或者你可以返回完整的resourceKey,当
//编辑资源文件(例如MyClass + SomeEnum.Small)
// return resourceKey;
}
else
return localizedDescription;
}
void SomeRoutine()
{
//查找资源文件中匹配关键字的
//MyClass + SomeEnum.Large
string s1 = EnumDescription(SomeEnum.Large);
}
}
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.
解决方案
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?
using System;
using System.Resources;
using System.Reflection;
public class MyClass
{
enum SomeEnum {Small,Large};
private ResourceManager _resources = new ResourceManager("MyClass.myResources",
System.Reflection.Assembly.GetExecutingAssembly());
public string EnumDescription(Enum enumerator)
{
string rk = String.Format("{0}.{1}",enumerator.GetType(),enumerator);
string localizedDescription = _resources.GetString(rk);
if (localizedDescription == null)
{
// A localized string was not found so you can either just return
// the enums value - most likely readable and a good fallback.
return enumerator.ToString();
// Or you can return the full resourceKey which will be helpful when
// editing the resource files(e.g. MyClass+SomeEnum.Small)
// return resourceKey;
}
else
return localizedDescription;
}
void SomeRoutine()
{
// Looks in resource file for a string matching the key
// "MyClass+SomeEnum.Large"
string s1 = EnumDescription(SomeEnum.Large);
}
}
这篇关于本地化枚举描述属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文