C# 获取枚举 Enum 变量值的 Description 属性

有些时候,某个方法的返回值是个枚举类型,比如描述登录结果:

public enum LoginResult
{
    Success,
    WrongPassword,
    UserNotExist,
    Forbidden,
    Unknown
}

当前段UI获取到登陆方法的返回结果时,就需要告诉用户登录是否成功、什么原因失败的。如果直接使用 ToString() 方式直接返回枚举变量的名称,显然不合适。通常的做法是使用各 switch 来转换,弊端是要写过多的代码;或者构造一个 string[] msg ,再根据 LoginResult 的 int 值来相应的取,弊端是类型的int值必须是连续的或者 string[] msg 的个数大于或等于 枚举类型的最大 int 值 ,一一对应起来也比较麻烦 。 在 枚举类型 Enum 中,不支持 DisplayNameAttribute,但支持 DescriptionAttribute ,所以要从 DescriptionAttribute 入手。写一个通用方法,取出 DescriptionAttribute 即可。当然,为了使用方便,我们使用 .NET 3.5+ 支持的 扩展方法来实现:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;
using System.Reflection;

namespace com.hetaoos.Utils.Extensions
{
    public static class Extensions
    {
        /// <summary>
        /// 获取枚举变量值的 Description 属性
        /// </summary>
        /// <param name="obj">枚举变量</param>
        /// <returns>如果包含 Description 属性,则返回 Description 属性的值,否则返回枚举变量值的名称</returns>
        public static string GetDescription(this object obj)
        {
            return GetDescription(obj, false);
        }

        /// <summary>
        /// 获取枚举变量值的 Description 属性
        /// </summary>
        /// <param name="obj">枚举变量</param>
        /// <param name="isTop">是否改变为返回该类、枚举类型的头 Description 属性,而不是当前的属性或枚举变量值的 Description 属性</param>
        /// <returns>如果包含 Description 属性,则返回 Description 属性的值,否则返回枚举变量值的名称</returns>
        public static string GetDescription(this object obj, bool isTop)
        {
            if (obj == null)
            {
                return string.Empty;
            }
            try
            {
                Type _enumType = obj.GetType();
                DescriptionAttribute dna = null;
                if (isTop)
                {
                    dna = (DescriptionAttribute)Attribute.GetCustomAttribute(_enumType, typeof(DescriptionAttribute));
                }
                else
                {
                    FieldInfo fi = _enumType.GetField(Enum.GetName(_enumType, obj));
                    dna = (DescriptionAttribute)Attribute.GetCustomAttribute(
                       fi, typeof(DescriptionAttribute));
                }
                if (dna != null && string.IsNullOrEmpty(dna.Description) == false)
                    return dna.Description;
            }
            catch
            {
            }
            return obj.ToString();
        }
    }
}

使用方法很简单:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using System.ComponentModel;
using com.hetaoos.Utils.Extensions;//这一句是必须的,否则无法使用扩展方法
using System.Diagnostics;

namespace com.hetaoos
{
    static class Program
    {
        /// <summary>
        /// 应用程序的主入口点。
        /// </summary>
        [STAThread]
        static void Main()
        {
            ProcessedDataResultType resultType = ProcessedDataResultType.BkgrdMap;
            ProcessedDataWaringResult ret = new ProcessedDataWaringResult() { ResultType = ProcessedDataResultType.WaringResult };
            Debug.Print("枚举类型的描述属性:{0}", resultType.GetDescription(true));
            Debug.Print("单个枚举变量的描述属性:{0} --> {1}", resultType, resultType.GetDescription());
            Debug.Print("类类型的描述属性:{0}", ret.GetDescription(true));
            Debug.Print("类类型的属性的描述属性:{0} --> {1}  --> {2}", ret.ResultType, ret.ResultType.GetDescription(), ret.ResultType.GetDescription(true));
        }

        /// <summary>
        /// 处理结果类型
        /// </summary>
        //[TypeConverter(typeof(EnumDescConverter))]
        [Description("处理后的数据类型")]
        public enum ProcessedDataResultType : byte
        {
            [Description("背景地图")]
            BkgrdMap,
            [Description("检测结果")]
            WaringResult
        }

        [Description("报警结果")]
        public class ProcessedDataWaringResult
        {
            [Description("结果类型")]
            public ProcessedDataResultType ResultType { get; set; }
        }
    }
}
输出结果如下:
枚举类型的描述属性:处理后的数据类型
单个枚举变量的描述属性:BkgrdMap --> 背景地图
类类型的描述属性:报警结果
类类型的属性的描述属性:WaringResult --> 检测结果  --> 处理后的数据类型
转自:http://blog.hetaoos.com/archives/41
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值