• c#枚举类型操作方法总结-1


    关于枚举类型用法总结两点,分享如下:

    1.  根据枚举值获取枚举值的描述信息,可以封装一个方法供调用:

    //  enumValue是传入的枚举值

    public string GetEnumDescrption(Enum enumValue)
    {
    string value = enumValue.ToString();
    FieldInfo field = enumValue.GetType().GetField(value);
    object[] objs = field.GetCustomAttributes(typeof(DescriptionAttribute),false);//获取描述属性
    //当描述没有时直接返回名称
    if (objs ==null || objs.Length ==0)
    {
    return value;
    }
    DescriptionAttribute descriptionAttribute = (DescriptionAttribute)objs[0];
    return descriptionAttribute.Description;
    }

    public static string GetEnumDescription(Enum enumValue, bool returnEnumAndDescription = true)
    {
    string str = enumValue.ToString();
    System.Reflection.FieldInfo field = enumValue.GetType().GetField(str);
    object[] objs = field.GetCustomAttributes(typeof(DescriptionAttribute), false);
    if (objs == null || objs.Length == 0) return str;
    DescriptionAttribute da = (DescriptionAttribute)objs[0];

    if (returnEnumAndDescription)//返回枚举值及描述
    {
    str = str + "_" + da.Description;
    }
    else
    {
    str = da.Description;//返回描述
    }

    return str;
    }

    枚举类型是:

    public enum EnumSex
    {
    /// <summary>
    /// 男
    /// </summary>
    [Description("男")]
    Male = 0,
    /// <summary>
    /// 女
    /// </summary>
    [Description("女")]
    Female = 1
    }

    调用方法如下:

    以控制台程序为例-

    Program program = new Program();
    string sex = program.GetEnumDescrption(EnumSex.Female);//sex ="女"
    Console.WriteLine(sex);

    2.for循环获取枚举值描述信息:

    枚举类型如下:

    public enum days
    {
    Monday,
    Tuesday,
    Wednesday,
    Thursday,
    Friday,
    Saturday,
    Sunday
    }

    调用方法如下:

    Type week = typeof(days);
    Array Arrays = Enum.GetValues(week);
    for (int i = 0; i < Arrays.LongLength; i++)
    {
    Console.WriteLine(Arrays.GetValue(i));
    }
    Console.Write("Press any key to continue . . . ");
    Console.ReadKey(true);

  • 相关阅读:
    iOS 整理面试题(上)
    2021年十大白马名单
    RabbitMQ:消息重复消费
    RabbitMQ:保证消息的顺序性
    RabbitMQ:保证消息的可靠性传输
    AWS S3 大文件分片上传
    rebase 用法小结
    Flask at scale
    MySQL分区
    动态规划示例题
  • 原文地址:https://www.cnblogs.com/newcapecjmc/p/10954572.html
Copyright © 2020-2023  润新知