检查变量是否与枚举相对应

本文关键字:相对 枚举 变量 是否 检查 | 更新日期: 2023-09-27 18:29:29

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

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

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

检查变量是否与枚举相对应

我认为您正在寻找Enum::IsDefined Method

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

更新:-

试试这样的东西:-

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

这应该有效:

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

您可以将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
}

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

Enum.GetName(typeof(AlertType), (AlertType)val) != null
if (Enum.IsDefined(typeof(AlertType), x))
{
    var enumVal = Enum.Parse(typeof(AlertType), x.ToString());
}
else
{
    //Value not defined
}