在.net中本地化枚举描述的最佳方法是什么?
(请参阅为枚举描述示例添加枚举常量的描述)
理想情况下,我想要使用ResourceManager和资源文件的东西,以便它适合应用程序的其他区域的本地化.
这就是我最终的目标,我没有看到添加自定义属性类来保存资源键然后查找资源文件的价值 - 为什么不直接使用枚举typename + value作为资源键?
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); } }
我的解决方案,使用本机描述属性:
public class LocalizedEnumAttribute : DescriptionAttribute { private PropertyInfo _nameProperty; private Type _resourceType; public LocalizedEnumAttribute(string displayNameKey) : base(displayNameKey) { } public Type NameResourceType { get { return _resourceType; } set { _resourceType = value; _nameProperty = _resourceType.GetProperty(this.Description, BindingFlags.Static | BindingFlags.Public); } } public override string Description { get { //check if nameProperty is null and return original display name value if (_nameProperty == null) { return base.Description; } return (string)_nameProperty.GetValue(_nameProperty.DeclaringType, null); } } } public static class EnumExtender { public static string GetLocalizedDescription(this Enum @enum) { if (@enum == null) return null; string description = @enum.ToString(); FieldInfo fieldInfo = @enum.GetType().GetField(description); DescriptionAttribute[] attributes = (DescriptionAttribute[])fieldInfo.GetCustomAttributes(typeof(DescriptionAttribute), false); if (attributes.Any()) return attributes[0].Description; return description; } }
Enum声明
public enum MyEnum { [LocalizedEnum("ResourceName", NameResourceType = typeof(ResourceType))] Test = 0 }
然后打电话 MyEnumInstance.GetLocalizedDescription()
有一个简单的解决方案:使用LocalizedDescription属性传递资源键.
[Serializable] public class LocalizableDescriptionAttribute:DescriptionAttribute { public LocalizableDescriptionAttribute(string resourceKey) :base(Resources.ResourceManager.GetString(resourceKey)) { } }