在 .net 中本地化枚举描述的最佳方法是什么?
(枚举描述示例参见 Adding descriptions to enumeration constants)
理想情况下,我想要使用 ResourceManager 和资源文件的东西,以便它适合应用程序其他区域的本地化方式。
最佳答案
这就是我最终要做的,我没有看到添加自定义属性类来保存资源键然后查找资源文件的值(value) - 为什么不直接使用枚举类型名 + 值作为资源 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);
}
}
关于c# - 本地化枚举描述属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/569298/