惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Y
Y Combinator Blog
The GitHub Blog
The GitHub Blog
云风的 BLOG
云风的 BLOG
Engineering at Meta
Engineering at Meta
Google DeepMind News
Google DeepMind News
aimingoo的专栏
aimingoo的专栏
Recent Announcements
Recent Announcements
A
About on SuperTechFans
U
Unit 42
MyScale Blog
MyScale Blog
J
Java Code Geeks
博客园_首页
Blog — PlanetScale
Blog — PlanetScale
D
Docker
Microsoft Azure Blog
Microsoft Azure Blog
博客园 - 司徒正美
量子位
月光博客
月光博客
G
Google Developers Blog
V
V2EX
博客园 - 聂微东
宝玉的分享
宝玉的分享
IT之家
IT之家
Vercel News
Vercel News

博客园 - 谢小漫

弹出选择窗体控件(附源码) mshtml组件引用的问题 导出所有用户表到excel Sql Server数据导出EXCEL C#的串口编程 DataReceived XML-RPC.NET的X509Certificates如何使用呢 XML-RPC.NET 在读《C#和.NET 2.0实战》 如何在ASP.NET中做异步 如何在winform中用委托做异步 C#的串口编程 重新开始学习.net 在看Test-Driven Development In Microsoft .NET 最近了解过的一个支付接口 网站的第三天 BAIDU的第一个搜索访问进入网站 不错的日期选择 星期六提交sitemap 关于代码自动生成器
获取枚举描述信息(Description)2 - 谢小漫 - 博客园
谢小漫 · 2009-09-23 · via 博客园 - 谢小漫

之前记录过一种获取枚举描述信息的方法:http://cat.xiexiao.com/enum_description/

今天,发现扩展一下Enum的方法更好,不过就是只能C#3.0才可以使用扩展方法。

1。定义enum
using System;
using System.ComponentModel;

  public enum TimeOfDay
        {
            [Description("上午")]
            Moning = 0,
            [Description("中午")]
            Afternoon = 1,
            [Description("晚上")]
            Evening = 2,
        };

2.定义扩展:

        /// <summary>
        /// 获取描述信息
        /// </summary>
        /// <param name="en"></param>
        /// <returns></returns>
        public static string description(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();
        }

这样子就可以直接用方法:.description()来获取描述信息了。没有描述信息,返回en.ToString()。

这里可以搞到wave邀请