我不知道该怎么做
我希望代码如下
enum myenum
{
name1 = "abc",
name2 = "xyz"
}
Run Code Online (Sandbox Code Playgroud)
并检查它
if (myenum.name1 == variable)
Run Code Online (Sandbox Code Playgroud)
我该怎么办?
感谢名单.
Jef*_*ado 14
不幸的是,这是不可能的.枚举只能有一个基本的基本类型(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...
}
Run Code Online (Sandbox Code Playgroud)
根据here,你正在做的事情是不可能的。你可以做的也许是拥有一个充满常量的静态类,也许像这样:
class Constants
{
public static string name1 = "abc";
public static string name2 = "xyz";
}
...
if (Constants.name1 == "abc")...
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
18930 次 |
| 最近记录: |