如何检查枚举是否包含一个数字? [英] How to check If a Enum contain a number?

查看:161
本文介绍了如何检查枚举是否包含一个数字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  public enum PromotionTypes 
{
未指定= 0,
InternalEvent = 1,
ExternalEvent = 2,
GeneralMailing = 3,
VisitBased = 4,
PlayerIntroduction = 5,
招待费= 6
}

我想检查这个枚举是否包含我给的号码。例如:当我给出4,Enum包含,所以我想返回True,如果我给7,这个枚举中没有7,所以它返回False。
我尝试过Enum.IsDefine,但它只检查String值。
我该怎么做?

解决方案

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

 枚举状态
{
OK = 0,
警告= 64,
错误= 256
}

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

//测试整数值
exists = Enum.IsDefined(typeof(Status),0); // exists = true
exists = Enum.IsDefined(typeof(Status),1); // exists = false

//测试常量名称
exists = Enum.IsDefined(typeof(Status),OK); // exists = true
exists = Enum.IsDefined(typeof(Status),NotOK); // exists = false
}

SOURCE


I have a Enum like this:

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

I want to check if this Enum contain a number I give. For example: When I give 4, Enum contain that, So I want to return True, If I give 7, There isn't 7 in this Enum, So it returns False. I tried Enum.IsDefine but it only check the String value. How can I do that?

解决方案

The IsDefined method requires two parameters. The first parameter is the type of the enumeration to be checked. This type is usually obtained using a typeof expression. The second parameter is defined as a basic object. It is used to specify either the integer value or a string containing the name of the constant to find. The return value is a Boolean that is true if the value exists and false if it does not.

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
}

SOURCE

这篇关于如何检查枚举是否包含一个数字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆