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. 枚举成员名称的字符串表示形式。字符串中的字符必须与枚举成员名称具有相同的大小写
  • 相关阅读:
    (.*?)懒惰正则
    re.S
    import和from import陷阱一
    import和from import陷阱二
    Linux中查看文件编码
    环境部署策略
    简便删除已经存在的oracle数据库用户UPAY3LINGXI_YS
    ssh连接linux服务器只显示-bash-4.1#不显示路径解决方法
    ubuntu安装出现"删除initramfs-tools时出错",subprocess installed post-installation script returned error exit status 1
    python下载链接内容
  • 原文地址:https://www.cnblogs.com/moonstars/p/15160779.html
Copyright © 2011-2022 走看看