【问题标题】:How to check If a Enum contain a number?如何检查枚举是否包含数字?
【发布时间】:2012-08-30 19:02:48
【问题描述】:

我有一个这样的枚举:

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

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

【问题讨论】:

标签: c# .net enums


【解决方案1】:

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
}

SOURCE

【讨论】:

    【解决方案2】:

    试试这个:

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

    【讨论】:

      【解决方案3】:

      你应该使用Enum.IsDefined

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

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

      【讨论】:

      • Thx,这是我的错误,我忘记将字符串转换为 Int,所以当我给出正确的数字时,Enum.isDefined 总是会出错。
      • 它绝对可以采用(区分大小写的字符串表示) - 更多信息请参见 the docsthe source
      【解决方案4】:

      也许你想检查和使用字符串值的枚举:

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

      【讨论】:

        猜你喜欢
        • 2021-09-25
        • 2011-06-23
        • 1970-01-01
        • 1970-01-01
        • 2014-08-09
        • 1970-01-01
        • 1970-01-01
        • 2015-02-12
        • 2017-11-30
        相关资源
        最近更新 更多