c# – 将枚举值与本地化字符串资源相关联
发布时间:2020-12-15 17:37:47 所属栏目:百科 来源:网络整理
导读:有关: 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(); } http://geekswithblogs.net/paulwhitblog/archive/2008/03/31/use-the-descriptionattribute-with-an-enum-to-display-status-messages.aspx 编辑:对评论的回应(@Tergiver).在我的示例中使用(现有)DescriptionAttribute是为了快速完成工作.您最好实现自己的自定义属性,而不是使用其目的之外的属性.像这样的东西: [AttributeUsage(AttributeTargets.Field,AllowMultiple = false,Inheritable = false)] public class EnumResourceKeyAttribute : Attribute { public string ResourceKey { get; set; } } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |