当前位置: 首页 > 编程语言 > C#

将枚举值与本地化字符串资源相链接分享

时间:2023-04-11 03:32:38 C#

C#学习教程:将枚举值链接到本地??化的字符串资源如果我将枚举和类放在同一个文件中,我会觉得有些安全,但我必须假设有更好的方法。我也考虑过使枚举名称与资源字符串名称相同,但恐怕我不能总是在这里强制执行。使用CR=AcmeCorp.Properties.Resources;publicenumSourceFilterOption{LastNumberOccurences,LastNumberWeeks,DateRange//如果你添加到这个你必须更新FilterOptions.GetString}publicclassFilterOptions{publicDictionaryGetEnumWithResourceString(){newdictforeach(SourceFilterOptionfilterinEnum.GetValues(typeof(SourceFilterOption))){dict.Add(过滤器,GetString(过滤器));}返回字典;}publicStringGetString(SourceFilterOptionoption){switch(option){caseSourceFilterOption.LastNumberOccurences:returnCR.LAST_NUMBER_OF_OCCURANCES;caseSourceFilterOption.LastNumberWeeks:返回CR.LAST_NUMBER_OF_WEEKS;caseSourceFilterOption.DateRange:默认:返回CR.DATE_RANGE;您可以添加DescriptionAttribute。publicenumSourceFilterOption{[Description("LAST_NUMBER_OF_OCCURANCES")]LastNumberOccurences,...}在需要时提取描述(资源键)。FieldInfofi=value.GetType().GetField(value.ToString());DescriptionAttribute[]属性=(DescriptionAttribute[])fi.GetCustomAttributes(typeof(DescriptionAttribute),if(attributes.Length>0){returnattributes[0].Description;}else{returnvalue.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)]publicclassEnumResourceKeyAttribute:Attribute{publicstringResourceKey{get;.publicStringGetString(SourceFilterOptionoption){switch(option){caseSourceFilterOption.LastNumberOccurences:returnCR.LAST_NUMBER_OF_OCCURANCES;caseSourceFilterOption.LastNumberWeeks:返回CR.LAST_NUMBER_OF_WEEKS;caseSourceFilterOption.DateRange:returnCR.DATE_RANGE;默认值:thrownewException("SourceFilterOption"+option+"wasnotfound");我通过以下方式映射到资源:1.使用ctor获取2个参数(资源类型及其名称)来定义StringDescription类[AttributeUsage(AttributeTargets.Field,AllowMultiple=false)]classStringDescriptionAttribute:Attribute{privatestring_name;公共StringDescriptionAttribute(字符串名称){_name=名称;}publicStringDescriptionAttribute(TyperesourceType,stringname){_name=newResourceManager(resourseType).GetString(name);}publicstringName{get{return_name;}}}为两种文化创建资源文件(例如WebTexts.resx和Webtexts.ru.resx)。让我们的颜色是红色,绿色等......定义枚举:enumColor{[StringDescription(typeof(WebTexts),"Red")]Red=1,[StringDescription(typeof(WebTexts),"Green")]Green=2,[StringDescription(typeof(WebTexts),"Blue")]Blue=3,[StringDescription("Antracitwithmaddarkcircles")]AntracitWithMadDarkCircles}定义静态方法通过反射获取资源描述publicstaticstringGetStringDescription(Enumen){varenumValueName=Enum.GetName(en.GetType(),en);FieldInfofi=en.GetType().GetField(enumValueName);varattr=(StringDescriptionAttribute)fi.GetCustomAttribute(typeof(StringDescriptionAttribute));返回attr!=null?属性名称:“”;吃:颜色col;col=Color.Red;Thread.CurrentThread.CurrentUICulture=newSystem.Globalization.CultureInfo("en-US");varListOfColors=typeof(Colour).GetEnumValues().Cast().Select(p=>new{Id=p,Decr=GetStringDescription(p)}).ToList();foreach(ListOfColors中的varlistentry)Debug.WriteLine(listentry.Id+“”+listentry.Decr);我想要这就是我实现它的方式首先你需要定义一个属性publicclassLocalizedDescriptionAttribute:DescriptionAttribute{privatereadonlystring_resourceKey;私有只读资源管理器_resource;publicLocalizedDescriptionAttribute(stringresourceKey,TyperesourceType){_resource=newResourceManager(resourceType);_resourceKey=resourceKey;}publicoverridestringDescription{get{stringdisplayName=_resource.GetString(_resourceKey);返回string.IsNullOrEmpty(displayName)?string.Format("[[{0}]]",_resourceKey):显示名称;您可以像这样使用属性publicenumOrderType{[LocalizedDescription("DineIn",typeof(Properties.Resources))]DineIn=1,[LocalizedDescription("Takeaway",typeof(Properties.Resources))]Takeaway=2}然后定义一个转换器返回enumValue==null?依赖dencyProperty.UnsetValue:enumValue.GetDescriptionFromEnumValue();}publicobjectConvertBack(objectvalue,TypetargetType,objectparameter,CultureInfolanguage){返回值;然后在您的XAML中,有一种最简单的方法可以从资源文件区域性转换为获取枚举描述值myenumpublicenumDiagnosisType{[Description("Nothing")]NOTHING=0,[Description("Advice")]ADVICE=1,[Description("Prescription")]PRESCRIPTION=2,[Description("Referral")]REFERRAL=3}我创建了资源文件,key与枚举描述值Resoucefile和EnumKey相同和ValueImage,点击查看资源文件imagepublicstaticstringGetEnumDisplayNameValue(Enumenumvalue){varname=enumvalue.ToString();varculture=Thread.CurrentThread.CurrentUICulture;varconverted=YourProjectNamespace.Resources.Resource.ResourceManager.GetString(name,culture);返回转换;}在YourNameSpace视图上调用此方法关于C#学习教程,希望大家多多关注。本文收集自网络,不代表立场。如涉及侵权,请点击右侧联系管理员删除。如有转载请注明出处: