zoukankan      html  css  js  c++  java
  • C#取枚举描述

    一直都觉得枚举是个很不错的东西,可以给我们带来很多方便,而且也增加代码的可读性。 我在之前已经介绍过枚举的简要应用了,再次再来写下怎么获取枚举的描述。 源码如下: 首先,我们定义个含有描述的枚举类型

    public enum Url{

        [Description("http://www.thylx.net")]       

        个人博客 1,

        [Description("http://blog.163.com/thylx133@126/")]

        网易博客 2,       

        [Description("http://www.8eshare.com/")]

        八邑分享 3

    }

    定义完枚举之后,我们来写个通用的方法获取枚举的描述信息

     

     

            /// <summary>

            /// 获取描述信息

            /// </summary>

            /// <param name="en">枚举</param>

            /// <returns></returns>

            public static string GetEnumDes(this Enum en) {

                    Type type = en.GetType();

                    MemberInfo[] memInfo = type.GetMember(en.ToString());

                    if (memInfo != null && memInfo.Length > 0)

                    {

                            object[] attrs = memInfo[0].GetCustomAttributes(typeof(System.ComponentModel.DescriptionAttribute), false);

                            if (attrs != null && attrs.Length > 0)

                            return ((DescriptionAttribute)attrs[0]).Description;

                    }          

                    return en.ToString();

           }

     

    以上通用方法便可获取到枚举的描述,调用方式如下:

    string strValue = GetEnumDes(Url.个人博客);

    此时的strValue 变量值为:http://www.thylx.net

  • 相关阅读:
    ES2017中的修饰器Decorator
    ES6中的模块
    代理(Proxy)和反射(Reflection)
    ES2017中的async函数
    ES6数字扩展
    Promise和异步编程
    ES6定型数组
    ES6数组扩展
    ES6中的类
    ES6中的Set和Map集合
  • 原文地址:https://www.cnblogs.com/xtt321/p/4866750.html
Copyright © 2011-2022 走看看