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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12291953/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 22:46:03  来源:igfitidea点击:

How to check If a Enum contain a number?

c#.netenums

提问by Hyman Zhang

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?

我想检查这个 Enum 是否包含我给出的数字。例如:当我给出 4 时,Enum 包含那个,所以我想返回 True,如果我给出 7,这个 Enum 中没有 7,所以它返回 False。我试过 Enum.IsDefine 但它只检查字符串值。我怎样才能做到这一点?

采纳答案by John Woo

The IsDefinedmethod 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.

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

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

来源

回答by horgh

Try this:

尝试这个:

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

回答by Cheng Chen

You should use Enum.IsDefined.

你应该使用Enum.IsDefined.

I tried Enum.IsDefine but it only check the String value.

我试过 Enum.IsDefine 但它只检查字符串值。

I'm 100% sure it will check both string value and int(the underlying) value, at least on my machine.

我 100% 肯定它会检查字符串值和 int(底层)值,至少在我的机器上。

回答by Hulzi

Maybe you want to check and use the enum of the string value:

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

string strType;
if(Enum.TryParse(strType, out MyEnum myEnum))
{
    // use myEnum
}