.net c#获取自定义Attribute

前言: 在c#开发中,有时候我们需要读取 Attribute中的信息(关于Attribute , 我自己把他理解成一个可以为类,属性标记的东西,这个标记可以为你提供一些关于类,方法,属性的额外信息)

我们如何获取这些标记的信息,如何获取自定义Attribute信息。

正文:

1.获取一个枚举的详细信息

假设我们有这样一个枚举

public enum Category
    {
        /// <summary>
        /// 英语
        /// </summary>
        English,
        /// <summary>
        /// 汉语
        /// </summary>
        Chinese,
        /// <summary>
        /// 日语
        /// </summary>
        Japanese
    }
现在我要获取每个枚举的描述信息。 如果你不了Attribute,或许你只能这样获取
static class Program
    {
        static void Main()
        {
            var category = Category.Chinese;
            switch (category)
            {
                case Category.Chinese: Console.WriteLine("中文"); break;
                case Category.English: Console.WriteLine("英文"); break;
                case Category.Japanese: Console.WriteLine("日语"); break;
            }
        }
    }

似乎几个Case语句也能完成任务。 但是如果枚举项个数超多,那这种写法无疑很丑陋。

----------------------------------华丽分割线------------------------------------

接下来探讨 Attribute的一种简单应用场景

修改枚举

public enum Category
    {
        /// <summary>
        /// 英语
        /// </summary>
        [Description("西洋文")]
        English,
        /// <summary>
        /// 汉语
        /// </summary>
        [Description("汉语")]
        Chinese,
        /// <summary>
        /// 日语
        /// </summary>
        [Description("日本话")]
        Japanese
    }

每个枚举项加入System.ComponentModel命名空间的 DescriptionAttribute,不清楚可以msdn一下。

然后附上两个算我原创的类吧...记得层在公司使用过直接获取 Descripton标记的方法,但是没有源码,我花了一天时间来查询这个问题,终于写出了自己的帮助类.奉献给大家..

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;

namespace ZyTools
{
    /// <summary>
    /// 枚举帮助类
    /// </summary>
    public class EnumHelper
    {
        /// <summary>
        /// 获取枚举项的Attribute
        /// </summary>
        /// <typeparam name="T">自定义的Attribute</typeparam>
        /// <param name="source">枚举</param>
        /// <returns>返回枚举,否则返回null</returns>
        public static T GetCustomAttribute<T>(Enum source) where T : Attribute
        {
            Type sourceType = source.GetType();
            string sourceName = Enum.GetName(sourceType, source);
            FieldInfo field = sourceType.GetField(sourceName);
            object[] attributes = field.GetCustomAttributes(typeof(T), false);
            foreach (object attribute in attributes)
            {
                if (attribute is T)
                    return (T)attribute;
            }
            return null;
        }

        /// <summary>
        ///获取DescriptionAttribute描述
        /// </summary>
        /// <param name="source">枚举</param>
        /// <returns>有description标记,返回标记描述,否则返回null</returns>
        public static string GetDescription(Enum source)
        {
            var attr = GetCustomAttribute<System.ComponentModel.DescriptionAttribute>(source);
            if (attr == null)
                return null;

            return attr.Description;
        }
    }
}
 

现在我们只需要,这样写代码了.

var category = Category.Chinese;

 Console.WriteLine(EnumHelper.GetDescription(category));

是不是很清爽 .希望本文对初学者有所帮助,来源于www.xiaoniusoft.com
,转摘请注明。爱编程爱生活!!!

时间: 2024-08-01 23:13:12

.net c#获取自定义Attribute的相关文章

获取自定义Attribute的Description

自定义Attribute /// <summary> /// 合同状态 /// </summary> public enum ContractStatus { [GlobalCode("新建")] Pending = 0, [GlobalCode("提交待审批")] AuditPending = 3, [GlobalCode("审批拒绝")] AuditReject = 6 } [AttributeUsage(Attrib

转:C#制作ORM映射学习笔记一 自定义Attribute类

之前在做unity项目时发现只能用odbc连接数据库,感觉非常的麻烦,因为之前做web开发的时候用惯了ORM映射,所以我想在unity中也用一下ORM(虽然我知道出于性能的考虑这样做事不好的,不过自己的小项目吗管他的,自己爽就行了).不过现在世面上的ORM映射基本都是为web项目设计的,与unity项目很难契合,所以我决定自己做一个简易的ORM映射.虽然想的很美但是实际做起来才发现还是挺复杂的,所以我在这里记录一下这次的开发过程,防止以后遗忘. 今天先记录一下如何通过自定义attribute类实

C#自定义Attribute值的获取与优化

C#自定义Attribute值的获取是开发中会经常用到的,一般我们的做法也就是用反射进行获取的,代码也不是很复杂. 1.首先有如下自定义的Attribute 1 [AttributeUsage(AttributeTargets.All)] 2 public sealed class NameAttribute : Attribute 3 { 4 private readonly string _name; 5 6 public string Name 7 { 8 get { return _na

c#自定义Attribute获取接口实现

原文:c#自定义Attribute获取接口实现 一般的接口实现多态 定义接口 interface Ipeople { void say(); } 定义实现的类 public class man : Ipeople { public void say() { MessageBox.Show("man"); } } public class woman : Ipeople { public void say() { MessageBox.Show("woman"); }

自定义Attribute,使用记录

1. 自定义attribute需要继承Attribute基类 /// <summary> /// Datareader反射使用 标记 /// 标记 属性在Datareader 中的字段名 以便反射赋值 /// </summary> [AttributeUsage(AttributeTargets.Property| AttributeTargets.Field)] public class DataReaderModelAttribute:Attribute { private s

CVS导出&amp;&amp;自定义Attribute的使用

1.cvs导出:List转为byte[] /// <summary> /// CvsExport帮助类 /// </summary> public static class CvsExportHelper { /// <summary> /// Creates the CSV from a generic list. /// </summary>; /// <typeparam name="T"></typeparam&

XsdGen:通过自定义Attribute与反射自动生成XSD

前言 系统之间的数据交互往往需要事先定义一些契约,在WCF中我们需要先编写XSD文件,然后通过自动代码生成工具自动生成C#对象.对于刚刚接触契约的人来说,掌握XMLSpy之类的软件之后确实比手写XML效率要高,但还是有些学习成本的.此外XML的tag太多,如果设计的类型属性过多,手写XSD也不太现实,很难专注于设计. 于是我想能不能先用C#写好类型,然后自动生成标准格式的XSD呢.经过三天左右的设计和实现,目前实现了以下功能: 1. 支持Class和Enum类型的设计 2. 支持基元类型.自定义

iOS开发小技巧--获取自定义的BarButtonItem中的自定义View的方法(customView)

如果BarButtonItem是通过[[UIBarButtonItem alloc] initWithCustomView:(nonnull UIView *)]方法设置的.某些情况下需要修改BarButtonItem中自定义View的某些属性,例如显示的文字或者显示的图片. 可以通过BarButtonItem的customView获取自定义的View.

【微信公众平台】订阅号无需认证获取自定义菜单功能

你是一个订阅号的运营者么?你还在为自己的宣传没有自定义菜单烦恼么?你还在为了你的个人微信订阅号无法认证而没有自定义菜单功能而痛苦么?那么不要着急,现在小志哥教你免费获取自定义菜单功能,不论你是个人的订阅号还是企业的,不论你是认证的还是没有认证的(当然认证的是不需要我的帮忙的,哈哈)! 公众帐号运营者点击"添加功能插件"后选择右下角的"自定义菜单"卡片可申请开通自定义菜单插件. 编辑自定义菜单功能时可选择"跳转到网页"和"发送消息&quo