我不知道该怎么做
我想要如下代码
enum myenum
{
name1 = "abc",
name2 = "xyz"
}
检查一下
if (myenum.name1 == variable)
我该怎么做?
谢谢。
最佳答案
很遗憾,这是不可能的。枚举只能有基本的底层类型(int
、uint
、short
等)。如果您想将枚举值与其他数据相关联,请将属性应用于值(例如 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...
}
关于c# - 枚举设置为字符串并在需要时获取字符串值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10426444/