我有一个这样的枚举:
public enum PromotionTypes
{
Unspecified = 0,
InternalEvent = 1,
ExternalEvent = 2,
GeneralMailing = 3,
VisitBased = 4,
PlayerIntroduction = 5,
Hospitality = 6
}
我想检查这个枚举是否包含我提供的数字。例如:当我给 4 时,Enum 包含它,所以我想返回 True,如果我给 7,这个 Enum 中没有 7,所以它返回 False。 我试过 Enum.IsDefine 但它只检查字符串值。 我怎样才能做到这一点?
最佳答案
IsDefined
方法需要两个参数。 第一个参数是要检查的枚举类型。这种类型通常使用 typeof 表达式获得。 第二个参数定义为基本对象。它用于指定整数值或包含要查找的常量名称的字符串。返回值是一个 bool 值,如果该值存在则为真,否则为假。
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
}
关于c# - 如何检查枚举是否包含数字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12291953/