如何检查如果一个枚举包含许多? [英] How to check If a Enum contain a number?

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

问题描述

我有一个枚举这样的:

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

我要检查如果该枚举包含一个数字,我给。例如:当我给4,枚举包含的,所以我想返回true,如果我给7,没有在此枚举7,所以返回False。 我想Enum.IsDefine但只检查字符串值。 我该怎么办呢?

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?

推荐答案

IsDefined 方法需要的两个参数的。在第一个参数是枚举要检查的类型。这种类型是使用typeof运算EX pression通常获得的。在第二个参数定义为基本对象。它用于指定任一整数值或含有恒定的查找名称的字符串。返回值是一个布尔值,如果是该值存在真假,如果它不。

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

SOURCE

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

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