有关:
Get enum from enum attribute
Get enum from enum attribute
我希望以最可维护的方式绑定枚举,并将它与关联的本地化字符串值相关联.
如果我把枚举和类放在同一个文件中,我觉得有些安全,但我必须假设有更好的方法.我还考虑过将枚举名称与资源字符串名称相同,但我担心我不能总是在这里强制执行.
using CR = AcmeCorp.Properties.Resources; public enum SourceFilterOption { LastNumberOccurences,LastNumberWeeks,DateRange // if you add to this you must update FilterOptions.GetString } public class FilterOptions { public Dictionary<SourceFilterOption,String> GetEnumWithResourceString() { var dict = new Dictionary<SourceFilterOption,String>(); foreach (SourceFilterOption filter in Enum.GetValues(typeof(SourceFilterOption))) { dict.Add(filter,GetString(filter)); } return dict; } public String GetString(SourceFilterOption option) { switch (option) { case SourceFilterOption.LastNumberOccurences: return CR.LAST_NUMBER_OF_OCCURANCES; case SourceFilterOption.LastNumberWeeks: return CR.LAST_NUMBER_OF_WEEKS; case SourceFilterOption.DateRange: default: return CR.DATE_RANGE; } } }
解决方法
您可以将DescriptionAttribute添加到每个枚举值.
public enum SourceFilterOption { [Description("LAST_NUMBER_OF_OCCURANCES")] LastNumberOccurences,... }
在需要时拉出描述(资源键).
FieldInfo fi = value.GetType().GetField(value.ToString()); DescriptionAttribute[] attributes = (DescriptionAttribute[])fi.GetCustomAttributes(typeof(DescriptionAttribute),if (attributes.Length > 0) { return attributes[0].Description; } else { return value.ToString(); }
编辑:对评论的回应(@Tergiver).在我的示例中使用(现有)DescriptionAttribute是为了快速完成工作.您最好实现自己的自定义属性,而不是使用其目的之外的属性.像这样的东西:
[AttributeUsage(AttributeTargets.Field,AllowMultiple = false,Inheritable = false)] public class EnumResourceKeyAttribute : Attribute { public string ResourceKey { get; set; } }