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

我有一个这样的 Enum:

 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,但它只检查 String 值。 我该怎么做?

117394 次浏览

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

Try this:

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

You should use Enum.IsDefined.

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

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

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

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

I use Enums.NET package.

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


((PromotionTypes)4).IsValid() == true;
((PromotionTypes)7).IsValid() == false;