IsDefined可以用于判断传入的单个值是否属于该枚举
GetValues检索指定枚举中常量值的数组
HasFlag 可以用于判断传入的多个值是否属于该枚举
先来个例子:
public enum BoilingPoints
{
Celsius = 100,
Fahrenheit = 212
};
[Flags]
public enum DinnerItems
{
None = 0,
Entree = 1,
Appetizer = 2,
Side = 4,
Dessert = 8,
Beverage = 16,
BarBeverage = 32
}
public class Program
{
public static void Main(String[] args)
{
/***
1. Enum.IsDefined(typeof(BoilingPoints), "Celsius")
2. Enum.IsDefined(typeof(BoilingPoints), BoilingPoints.Celsius)
3.Enum.IsDefined(typeof(BoilingPoints), 3)
*/
if (Enum.IsDefined(typeof(BoilingPoints), 4))
{
Console.WriteLine("TRUE:所传值在枚举中!");
}
else
{
Console.WriteLine($"FALSE:所传值在枚举中!");
}
//GetValues
foreach (var value in Enum.GetValues(typeof(BoilingPoints)))
{
Console.WriteLine($"{(int)value}, {(BoilingPoints)value}");
}
//HasFlag
DinnerItems myOrder = DinnerItems.Appetizer | DinnerItems.Entree |
DinnerItems.Beverage | DinnerItems.Dessert;
DinnerItems flagValue = DinnerItems.Entree | DinnerItems.Beverage | DinnerItems.Dessert;
Console.WriteLine($"{myOrder} includes {flagValue}: {myOrder.HasFlag(flagValue)}");
public static bool IsDefined (Type enumType, object value);
其中enumType是枚举类型,
其中value是可以是下面的任何一种:
- 类型的任何成员enumType
- 一个变量,其值为 type 的枚举成员enumType
- 枚举成员名称的字符串表示形式。字符串中的字符必须与枚举成员名称具有相同的大小写