• .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. 枚举成员名称的字符串表示形式。字符串中的字符必须与枚举成员名称具有相同的大小写
  • 相关阅读:
    密码加密
    注册视图
    session会话
    验证码功能
    使用Django表单替代html表单
    实现登陆视图功能
    设计登陆需求页面
    配置视图
    配置数据库
    npm 学习
  • 原文地址:https://www.cnblogs.com/moonstars/p/15160779.html
Copyright © 2020-2023  润新知