我有一个这样的枚举:
public enum PromotionTypes
{
Unspecified = 0,
InternalEvent = 1,
ExternalEvent = 2,
GeneralMailing = 3,
VisitBased = 4,
PlayerIntroduction = 5,
Hospitality = 6
}
Run Code Online (Sandbox Code Playgroud)
我想检查这个Enum是否包含我给出的数字.例如:当我给4时,Enum包含它,所以我想返回True,如果我给7,这个枚举中没有7,所以它返回False.我尝试了Enum.IsDefine,但它只检查String值.我怎样才能做到这一点?
Joh*_*Woo 143
该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
}
Run Code Online (Sandbox Code Playgroud)
试试这个:
IEnumerable<int> values = Enum.GetValues(typeof(PromotionTypes))
.OfType<PromotionTypes>()
.Select(s => (int)s);
if(values.Contains(yournumber))
{
//...
}
Run Code Online (Sandbox Code Playgroud)
小智 5
也许您想检查并使用字符串值的枚举:
string strType;
if(Enum.TryParse(strType, out MyEnum myEnum))
{
// use myEnum
}
Run Code Online (Sandbox Code Playgroud)