如何检查枚举是否包含数字?


79

我有一个这样的枚举:

 public enum PromotionTypes
{
    Unspecified = 0, 
    InternalEvent = 1,
    ExternalEvent = 2,
    GeneralMailing = 3,  
    VisitBased = 4,
    PlayerIntroduction = 5,
    Hospitality = 6
}

我想检查此枚举是否包含我提供的数字。例如:当我给出4时,Enum包含该值,因此我想返回True,如果我给出7,则此Enum中没有7,因此它返回False。我尝试了Enum.IsDefine,但它仅检查String值。我怎样才能做到这一点?


Answers:


176

IsDefined方法需要两个参数。第一个参数是要检查的枚举的类型。通常使用typeof表达式获得此类型。的第二个参数被定义为基本对象。它用于指定整数值或包含要查找的常量名称的字符串。返回值是一个布尔值,如果存在则返回true,否则返回false。

enum Status
{
    OK = 0,
    Warning = 64,
    Error = 256
}

static void Main(string[] args)
{
    bool exists;

    // Testing for Integer Values
    exists = Enum.IsDefined(typeof(Status), 0);     // exists = true
    exists = Enum.IsDefined(typeof(Status), 1);     // exists = false

    // Testing for Constant Names
    exists = Enum.IsDefined(typeof(Status), "OK");      // exists = true
    exists = Enum.IsDefined(typeof(Status), "NotOK");   // exists = false
}

资源


8

试试这个:

IEnumerable<int> values = Enum.GetValues(typeof(PromotionTypes))
                              .OfType<PromotionTypes>()
                              .Select(s => (int)s);
if(values.Contains(yournumber))
{
      //...
}

7

您应该使用Enum.IsDefined

我尝试了Enum.IsDefine,但它仅检查String值。

我100%肯定会至少在我的机器上同时检查字符串值和int(基础)值。


1
谢谢,这是我的错,我忘记了将字符串转换为Int的功能,所以当我输入正确的数字时,Enum.isDefined始终为false。
杰克张

它绝对可以采用(区分大小写的字符串表示形式)-有关更多信息,请参阅文档
怀河李

4

也许您想检查并使用字符串值的枚举:

string strType;
if(Enum.TryParse(strType, out MyEnum myEnum))
{
    // use myEnum
}
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.