复合枚举在 C# 中的常见操作

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/yenange/article/details/83989011
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Reflection;
using System.Text;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            List<UserInfo> list = new List<UserInfo>() {
                new UserInfo() { UserId = 1, UserName = "王明", UserType =(UserType) 2 },
                new UserInfo() { UserId = 2, UserName = "李丽", UserType =(UserType) 6 }
            };

            foreach (var item in list)
            {
                Console.WriteLine(item.ToString());
            }
            Console.Read();
        }
    }

    public class UserInfo
    {
        public long UserId { get; set; }

        public string UserName { get; set; }

        public UserType UserType { get; set; }

        public string UserTypeDesc
        {
            get
            {
                return EnumHelper.GetCompoundEnumDesc(typeof(UserType), Convert.ToInt32(this.UserType)) ;
            }
        }

        public UserType FirstType
        {
            get
            {
                return (UserType)EnumHelper.GetFirstEnumValueForCompound(typeof(UserType), Convert.ToInt32(this.UserType));
            }
        }

        public string FirstTypeDesc
        {
            get
            {
                return Convert.ToInt32(this.FirstType).ToEnumDescriptionString(typeof(UserType));
            }
        }

        public List<UserType> UserTypeList
        {
            get
            {
                List<UserType> rList = new List<UserType>();
                EnumHelper.GetSingleEnumValueListForCompound(typeof(UserType), Convert.ToInt32(this.UserType))
                    .ForEach(item =>
                    {
                        rList.Add((UserType)item);
                    });
                return rList;
            }
        }

        public string UserTypeListDesc
        {
            get
            {
                StringBuilder sb = new StringBuilder();
                int i = 1;
                foreach (var item in this.UserTypeList)
                {
                    sb.AppendFormat("\r\n{0}.{1}", i++, item.ToString());
                }
                return sb.ToString();
            }
        }

        public override string ToString()
        {
            return 
$@"UserId:{UserId}
UserName:{UserName}
UserType:{UserType}
UserTypeDesc:{UserTypeDesc}
FirstType:{FirstType}
FirstTypeDesc:{FirstTypeDesc}
UserTypeListDesc:{UserTypeListDesc}
";
        }
    }

    public enum UserType
    {
        [Description("普通用户")]
        Common = 1,
        [Description("家长")]
        Parent = 2,
        [Description("老师")]
        Teacher = 4
    }

    /// <summary>
    /// Author: yenange
    /// Date: 2014-04-11
    /// Description: 枚举辅助类
    /// </summary>
    public static class EnumHelper
    {
        /// <summary>
        /// 扩展方法:根据枚举值得到相应的枚举定义字符串
        /// </summary>
        /// <param name="value"></param>
        /// <param name="enumType"></param>
        /// <returns></returns>
        public static String ToEnumString(this int value, Type enumType)
        {
            NameValueCollection nvc = GetEnumStringFromEnumValue(enumType);
            return nvc[value.ToString()];
        }

        /// <summary>
        /// 根据枚举类型得到其所有的 值 与 枚举定义字符串 的集合
        /// </summary>
        /// <param name="enumType"></param>
        /// <returns></returns>
        public static NameValueCollection GetEnumStringFromEnumValue(Type enumType)
        {
            NameValueCollection nvc = new NameValueCollection();
            Type typeDescription = typeof(DescriptionAttribute);
            System.Reflection.FieldInfo[] fields = enumType.GetFields();
            string strText = string.Empty;
            string strValue = string.Empty;
            foreach (FieldInfo field in fields)
            {
                if (field.FieldType.IsEnum)
                {
                    strValue = ((int)enumType.InvokeMember(field.Name, BindingFlags.GetField, null, null, null)).ToString();
                    nvc.Add(strValue, field.Name);
                }
            }
            return nvc;
        }

        /// <summary>
        /// 扩展方法:根据枚举值得到属性Description中的描述, 如果没有定义此属性则返回空串
        /// </summary>
        /// <param name="value"></param>
        /// <param name="enumType"></param>
        /// <returns></returns>
        public static String ToEnumDescriptionString(this int value, Type enumType)
        {
            NameValueCollection nvc = GetNVCFromEnumValue(enumType);
            return nvc[value.ToString()];
        }

        /// <summary>
        /// 根据枚举类型得到其所有的 值 与 枚举定义Description属性 的集合
        /// </summary>
        /// <param name="enumType"></param>
        /// <returns></returns>
        public static NameValueCollection GetNVCFromEnumValue(Type enumType)
        {
            NameValueCollection nvc = new NameValueCollection();
            Type typeDescription = typeof(DescriptionAttribute);
            System.Reflection.FieldInfo[] fields = enumType.GetFields();
            string strText = string.Empty;
            string strValue = string.Empty;
            foreach (FieldInfo field in fields)
            {
                if (field.FieldType.IsEnum)
                {
                    strValue = ((int)enumType.InvokeMember(field.Name, BindingFlags.GetField, null, null, null)).ToString();
                    object[] arr = field.GetCustomAttributes(typeDescription, true);
                    if (arr.Length > 0)
                    {
                        DescriptionAttribute aa = (DescriptionAttribute)arr[0];
                        strText = aa.Description;
                    }
                    else
                    {
                        strText = "";
                    }
                    nvc.Add(strValue, strText);
                }
            }
            return nvc;
        }

        /// <summary>
        /// 从复合枚举中获取单个的枚举值列表
        /// </summary>
        /// <param name="enumType"></param>
        /// <param name="modelValue"></param>
        /// <returns></returns>
        public static List<int> GetSingleEnumValueListForCompound(Type enumType, int modelValue)
        {
            List<int> list = new List<int>();
            foreach (int enumValue in System.Enum.GetValues(enumType))
            {
                if ((enumValue & modelValue) == enumValue)
                    list.Add(enumValue); ;
            }
            return list;
        }

        /// <summary>
        /// 获取复合枚举的 Description 属性的所有内容,多个以逗号隔开
        /// </summary>
        /// <param name="enumType"></param>
        /// <param name="modelValue"></param>
        /// <returns></returns>
        public static string GetCompoundEnumDesc(Type enumType, int modelValue)
        {
            StringBuilder sb = new StringBuilder();
            foreach (int enumValue in System.Enum.GetValues(enumType))
            {
                if ((enumValue & modelValue) == enumValue)
                    sb.Append(enumValue.ToEnumDescriptionString(enumType) + ",");
            }
            return sb.ToString().TrimEnd(',');
        }

        /// <summary>
        /// 获取复合枚举的第一个单枚举的对应值,如获取失败,返回 -987654321
        /// </summary>
        /// <param name="enumType"></param>
        /// <param name="modelValue"></param>
        /// <returns></returns>
        public static int GetFirstEnumValueForCompound(Type enumType, int modelValue)
        {
            foreach (int enumValue in Enum.GetValues(enumType))
            {
                if ((enumValue & modelValue) == enumValue)
                {
                    return enumValue;
                }
            }
            return -987654321;
        }
    }//end of class
}

猜你喜欢

转载自blog.csdn.net/yenange/article/details/83989011