C# 简单判断枚举值是否被定义

C#枚举类有自带的函数用来判断是否被定义:

bool IsDefined(Type enumType, object value)

IsDefined(Type, Object)

返回一个布尔值,该值指示给定的整数值或其名称字符串是否存在于指定的枚举中。

参数类型,可以是枚举值、枚举名、枚举实例。

其实,也可以通过其他的方式快速判断:

Enum.GetName(typeof(ETimeType), eType) != null

GetName(Type, Object)

在指定枚举中检索具有指定值的常数的名称。

Array.IndexOf(Enum.GetValues(typeof(ETimeType)), eType) <= 0

GetValues(Type)

检索指定枚举中常数值的数组。

enum ETimeType
{
    WEEK = 1,   //每周几
    DAY_INTERVAL = 2,   //天数间隔
    NATURE = 3,     //自然
}

public static void test()
{
    Console.WriteLine("----IsDefined: " + Enum.IsDefined(typeof(ETimeType), 2));  //True
    Console.WriteLine("----IsDefined: " + Enum.IsDefined(typeof(ETimeType), "NATURE"));  //True
    Console.WriteLine("----IsDefined: " + Enum.IsDefined(typeof(ETimeType), (ETimeType)2));  //True
    Console.WriteLine("----IsDefined: " + Enum.IsDefined(typeof(ETimeType), new ETimeType()));  //False, new ETimeType()其实是整数0

    Console.WriteLine("----IsDefined: " + Enum.GetName(typeof(ETimeType), 2));  //NATURE
    Console.WriteLine("----IsDefined: " + Array.IndexOf(Enum.GetValues(typeof(ETimeType)), (ETimeType)2));  //2
}

还有一个用起来比较容易混淆的方法:

Enum.TryParse(typeof(ETimeType), "Other", false, out eType)

Parse(Type, String, Boolean)

将一个或多个枚举常数的名称或数字值的字符串表示转换成等效的枚举对象。 一个参数指定该操作是否不区分大小写。

public static void test()
{
    Console.WriteLine("----IsDefined: " + Enum.TryParse(typeof(ETimeType), "NATURE", false, out var evalue));  //True
    Console.WriteLine("----IsDefined: " + Enum.TryParse(typeof(ETimeType), "2", false, out evalue));  //True
    Console.WriteLine("----IsDefined: " + Enum.TryParse(typeof(ETimeType), "Other", false, out evalue));  //False
    Console.WriteLine("----IsDefined: " + Enum.TryParse(typeof(ETimeType), "4", false, out evalue));  //True
}

其实parse 4 的时候,返回的并不是一个ETimeType的值,但是TryParse的返回结果是true。这个方法只是返回了一个等效的可枚举对象,但并不代表被定义在这个枚举类型中。


版权声明:本文为aleefang原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。