枚举设置为string并在需要时获取sting值 [英] enum set to string and get sting value when need
本文介绍了枚举设置为string并在需要时获取sting值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我不知道该怎么做
我想要如下代码
enum myenum
{
name1 =abc,
name2 =xyz
}
并查看
if(myenum.name1 == variable)
$ c $
$ b $ b
解决方案不幸的是,这是不可能的。枚举只能有一个基本的底层类型( int
, uint
, short
等)。如果要将枚举值与其他数据相关联,请将属性应用于值(例如 DescriptionAttribute
)。
public static class EnumExtensions
{
public static TAttribute GetAttribute< TAttribute>(此枚举值)
其中TAttribute:Attribute
{
var type = value.GetType();
var name = Enum.GetName(type,value);
return type.GetField(name)
.GetCustomAttributes(false)
.OfType< TAttribute>()
.SingleOrDefault();
}
public static String GetDescription(此枚举值)
{
var description = GetAttribute< DescriptionAttribute>(value);
return description!= null? description.Description:null;
}
}
枚举MyEnum
{
[描述(abc)] Name1,
[描述(xyz) ] Name2,
}
var value = MyEnum.Name1;
if(value.GetDescription()==abc)
{
// do stuff ...
}
/ pre>
I don't know how to do this
I want code like following
enum myenum
{
name1 = "abc",
name2 = "xyz"
}
and check it
if (myenum.name1 == variable)
how can I do those things?
thanx.
解决方案 Unfortunately that's not possible. Enums can only have a basic underlying type (int
, uint
, short
, etc.). If you want to associate the enum values with additional data, apply attributes to the values (such as the DescriptionAttribute
).
public static class EnumExtensions
{
public static TAttribute GetAttribute<TAttribute>(this Enum value)
where TAttribute : Attribute
{
var type = value.GetType();
var name = Enum.GetName(type, value);
return type.GetField(name)
.GetCustomAttributes(false)
.OfType<TAttribute>()
.SingleOrDefault();
}
public static String GetDescription(this Enum value)
{
var description = GetAttribute<DescriptionAttribute>(value);
return description != null ? description.Description : null;
}
}
enum MyEnum
{
[Description("abc")] Name1,
[Description("xyz")] Name2,
}
var value = MyEnum.Name1;
if (value.GetDescription() == "abc")
{
// do stuff...
}
这篇关于枚举设置为string并在需要时获取sting值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文