生活随笔
收集整理的這篇文章主要介紹了
C# 简单判断枚举值是否被定义
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
C#枚舉類有自帶的函數(shù)用來(lái)判斷是否被定義:
bool IsDefined(Type enumType, object value)
| IsDefined(Type, Object) | 返回一個(gè)布爾值,該值指示給定的整數(shù)值或其名稱字符串是否存在于指定的枚舉中。 |
參數(shù)類型,可以是枚舉值、枚舉名、枚舉實(shí)例。
其實(shí),也可以通過(guò)其他的方式快速判斷:
Enum.GetName(typeof(ETimeType), eType) != null
| GetName(Type, Object) | 在指定枚舉中檢索具有指定值的常數(shù)的名稱。 |
Array.IndexOf(Enum.GetValues(typeof(ETimeType)), eType) <= 0
| GetValues(Type) | 檢索指定枚舉中常數(shù)值的數(shù)組。 |
enum ETimeType
{WEEK = 1, //每周幾DAY_INTERVAL = 2, //天數(shù)間隔NATURE = 3, //自然
}public static void test()
{Console.WriteLine("----IsDefined: " + Enum.IsDefined(typeof(ETimeType), 2)); //TrueConsole.WriteLine("----IsDefined: " + Enum.IsDefined(typeof(ETimeType), "NATURE")); //TrueConsole.WriteLine("----IsDefined: " + Enum.IsDefined(typeof(ETimeType), (ETimeType)2)); //TrueConsole.WriteLine("----IsDefined: " + Enum.IsDefined(typeof(ETimeType), new ETimeType())); //False, new ETimeType()其實(shí)是整數(shù)0Console.WriteLine("----IsDefined: " + Enum.GetName(typeof(ETimeType), 2)); //NATUREConsole.WriteLine("----IsDefined: " + Array.IndexOf(Enum.GetValues(typeof(ETimeType)), (ETimeType)2)); //2
}
還有一個(gè)用起來(lái)比較容易混淆的方法:
Enum.TryParse(typeof(ETimeType), "Other", false, out eType)
| Parse(Type, String, Boolean) | 將一個(gè)或多個(gè)枚舉常數(shù)的名稱或數(shù)字值的字符串表示轉(zhuǎn)換成等效的枚舉對(duì)象。 一個(gè)參數(shù)指定該操作是否不區(qū)分大小寫(xiě)。 |
public static void test()
{Console.WriteLine("----IsDefined: " + Enum.TryParse(typeof(ETimeType), "NATURE", false, out var evalue)); //TrueConsole.WriteLine("----IsDefined: " + Enum.TryParse(typeof(ETimeType), "2", false, out evalue)); //TrueConsole.WriteLine("----IsDefined: " + Enum.TryParse(typeof(ETimeType), "Other", false, out evalue)); //FalseConsole.WriteLine("----IsDefined: " + Enum.TryParse(typeof(ETimeType), "4", false, out evalue)); //True
}
其實(shí)parse 4 的時(shí)候,返回的并不是一個(gè)ETimeType的值,但是TryParse的返回結(jié)果是true。這個(gè)方法只是返回了一個(gè)等效的可枚舉對(duì)象,但并不代表被定義在這個(gè)枚舉類型中。
總結(jié)
以上是生活随笔為你收集整理的C# 简单判断枚举值是否被定义的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
如果覺(jué)得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。