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

如何在C#中将字符串而不是整数值分配给字符串?分享

时间:2023-04-10 11:59:56 C#

C#中如何给字符串赋值而不是整数值?我正在尝试将一个字符串分配给一个枚举。就像下面的例子:enumMyEnum{first="FirstValue",second="SecondValue",third="ThirdValue"}所以我可以在我的代码中有这样的东西:MyEnumenumVar=MyEnum.first;...stringenumValue=EnumVar.ToString();//返回“第一个值”在传统方式中,当我创建一个枚举时,ToString()将返回枚举名称而不是它的值。所以这是不可取的,因为我正在寻找一种分配字符串值然后从枚举中获取该字符串值的方法。您可以在枚举中添加Description属性。enumMyEnum{[Description("FirstValue")]first,[Description("SecondValue")]second,[Description("ThirdValue")]third,}然后有一个方法返回你的描述。publicstaticstringGetEnumDescription(Enumvalue){FieldInfofi=value.GetType().GetField(value.ToString());DescriptionAttribute[]attributes=(DescriptionAttribute[])fi.GetCustomAttributes(typeof(DescriptionAttribute),false);if(attributes!=null&&attributes.Length>0)returnattributes[0].Description;否则返回值.ToString();然后你可以这样做:MyEnumenumVar=MyEnum.frist;字符串值=GetEnumDescription(enumVar);该值将保存“第一个值”您可能会看到:AssociatingastringwithanenuminC#{publicstaticreadonlystringFirst="FirstValue";publicstaticreadonlystringSecond="第二值";publicstaticreadonlystringThird="第三值";你不能那样做。枚举基于整数,而不是字符串。批准的枚举类型是byte、sbyte、short、ushort、int、uint、long或ulong。所以像字符串一样,你唯一能做的就是enumMyEnum{first,second,third}MyEnum.first.ToString();或者更喜欢使用反射并将描述用作枚举中字段的属性。enumMyEnum{FirstValue,//默认值为0SecondValue,//1ThirdValue//2}stringstr1=Enum.GetName(typeof(MyEnum),0);//将返回FirstValuestringstr2=Enum.GetName(typeof(MyEnum),MyEnum.SecondValue);//SecondValue如果需要像空格这样的完整字符串,需要加上describe方法。我还建议只创建一个查找字典。以上就是C#学习教程:C#中如何给字符串赋值而不是整数值?分享的所有内容,如果对你有用,需要了解更多C#学习教程,希望大家多多关注——stringvalue=MyLookupTable.GetValue(1);//第一个值value=MyLookupTable.GetValue(2);//第二个Valuevalue=MyLookupTable.GetValue(3);//第三个值类MyLookupTable{privatestaticDictionarylookupValue=null;privateMyLookupTable(){}publicstaticstringGetValue(intkey){if(lookupValue==null||lookupValue.Count==0)AddValues();如果(lookupValue.ContainsKey(key))返回lookupValue[key];否则返回字符串。空;//抛出异常}privatestaticvoidAddValues(){if(lookupValue==null){lookupValue=newDictionary();lookupValue.Add(1,"第一个值");lookupValue.Add(2,"第二个值");lookupValue.Add(3,"第三个值");}}}收藏不代表立场,如涉及侵权,请点击右侧联系管理员删除。如需转载请注明出处: