zoukankan      html  css  js  c++  java
  • .net Core IsDefined、GetValues、HasFlag 使用

    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是可以是下面的任何一种:
    1. 类型的任何成员enumType
    2. 一个变量,其值为 type 的枚举成员enumType
    3. 枚举成员名称的字符串表示形式。字符串中的字符必须与枚举成员名称具有相同的大小写
  • 相关阅读:
    Beta冲刺(5/7)——2019.5.26
    Beta冲刺(4/7)——2019.5.25
    Beta冲刺(3/7)——2019.5.24
    Echo团队Beta冲刺随笔集合
    Echo团队Alpha冲刺随笔集合
    用户体验报告(Echo)
    Echo团队 对 待就业六人组 和 SkyReach 的Beta产品测试报告
    Beta冲刺第七天
    Beta冲刺第六天
    Beta冲刺第五天
  • 原文地址:https://www.cnblogs.com/moonstars/p/15160779.html
Copyright © 2011-2022 走看看