C# 检查变量是否与枚举对应

C# 检查变量是否与枚举对应,c#,C#,假设我有int val=1检查该值是否与枚举对应的最佳方法是什么。以下是一个示例枚举: public enum AlertType { Success=1, Warning=2, Error=3 }; 我正在寻找一个具有最佳可维护性的答案 您可以将您的enum选项强制转换为int进行该检查: const int val = 1; if (val == (int)AlertType.Success) { // Do stuff } else if (va

假设我有
int val=1检查该值是否与枚举对应的最佳方法是什么。以下是一个示例枚举:

public enum AlertType 
{ 
    Success=1, 
    Warning=2, 
    Error=3 
};

我正在寻找一个具有最佳可维护性的答案

您可以将您的
enum
选项强制转换为
int
进行该检查:

const int val = 1;
if (val == (int)AlertType.Success)
{
    // Do stuff
}
else if (val == (int) AlertType.Warning)
{
    // Do stuff
}
else if (val == (int) AlertType.Error)
{
    // Do stuff
}
这应该起作用:

Int32 val = 1;
if (Enum.GetValues(typeof(AlertType)).Cast<Int32>().Contains(val))
{
}
Int32 val=1;
if(Enum.GetValues(typeof(AlertType)).Cast()包含(val))
{
}

我想你在找

返回是否存在具有指定值的常量的指示 在指定的枚举中

更新:-

试着这样做:-

 if(Enum.IsDefined(typeof(AlertType), val)) {}

除了提供的其他解决方案外,还有另一种简单的检查方法:

Enum.GetName(typeof(AlertType), (AlertType)val) != null

您正在寻找Enum::IsDefined方法吗?我知道我可以这样做,我想知道是否有更好的方法。那么您的问题应该提到您正在寻找其他方法。@apfunk然后包括您尝试的内容和预期的输出。“不会读心。@皮埃尔,但这显然是一个冗长而糟糕的解决方案。@ChrisSinclair-hahaha抱歉,完全没有理解这是一个讽刺。”。该死的,这是最好的答案。请使用实际代码更新您的答案:
如果(Enum.IsDefined(typeof(AlertType),val)){}
一旦您知道它存在,您可以使用
(AlertType)x
x
转换为
AlertType
if (Enum.IsDefined(typeof(AlertType), x))
{
    var enumVal = Enum.Parse(typeof(AlertType), x.ToString());
}
else
{
    //Value not defined
}