一、概述

Attribute说白了就是一个类而已,里边一般含有一些附加信息,或者一些特殊的处理逻辑,以便告诉编译器应用该特性的东东是个奇葩,需要特殊对待!

二、使用时的注意事项

2.1. Attribute是一个类,必须继承自System.Attribute

2.2 Attribute命名规范
Attribute命名一般以Attribute结尾, 但是在具体使用时候,可以省去Attribute这一后缀。加入定义了一个HelperAttribute, 具体使用的时候,可以这样写[Helper].

2.3 Attribute的使用限制
Attribute类在定义的时候,可以指定这个Attribute的应用范围,AttributeTargets枚举就列出了可以指定的范围,可以是class, field等;AllowMutiple为true或者false,意思就是是否让该特性在某个地方重复使用(比如在某一个类上使用多次);Inherited为true或者false,意思就是该特性是否会被应用该特性的类的子类继承。

2.4 Attribute中的参数赋值

位置参数(Attribute构造函数的参数):必填,且顺序要一致!

命名参数(Attribute中的其他字段或者属性):在使用时可以省略!

三、自定义一个Attribute并读取其值

举个栗子:

[AttributeUsage(AttributeTargets.Class, AllowMutiple=true, Inherited=false)]
 public class BookAttribute:Attribute
    {
        public string Msg { get; set; }
        public double Version = 1.0;
        public MyFirstAttribute(string msg)
         {
             Msg= msg;
         }
    }

通过反射获取Attribute相关信息:

namespace TestAttribute
  {
//多次使用特性类 [Book("人民邮电")]
[Book("北京")]
  class BookInfo
  {
   public string bookinfo = "图书信息";
   //构造函数
  public BookInfo()
  {   }
  }
  }
static void Main(string[] args)
{
BookInfo bookinfo = new BookInfo();
MemberInfo typeinfo = typeof(BookInfo);
    object[] bookarr= typeinfo.GetCustomAttributes(typeof(BookAttribute), false);
  if (bookarr.GetLength() != )
{
BookAttribute bookattribute1 = (BookAttribute)bookarr[];
BookAttribute bookattribute2 = (BookAttribute)bookarr[];
Console.WriteLine(bookinfo.bookinfo);
Console.WriteLine("出版社为:" + bookattribute1.Msg+ "城市为:" + bookattribute2.Msg);
Console.ReadKey();
}
}

四、学会使用一些.NET内置特性

举个栗子:

System.ObsoleteAttribute:告诉编译器某个方法已经过时,然后当编译器发现程序中有地方在使用这个用Obsolete标记过的方法时,就会给出一个警告信息。

public class TestClass
{
// 添加Obsolete特性
[Obsolete("请使用新的SendMsg(Message msg)重载方法")]
public static void ShowMsg()
{
Console.WriteLine("这是旧的SendMsg()方法");
}
}
private void button1_Click(object sender, EventArgs e)
{
TestClass.ShowMsg();
}

现在运行这段代码,我们会发现编译器给出了一个警告!

五、特性在枚举上的应用

enum Gender
{
[Description(“男”)]
Man, [Description(“女”)]
Woman
};
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection; namespace MyTools
{
/// <summary>
/// 枚举帮助类
/// </summary>
public static 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(this Enum source)
{
var attr = GetCustomAttribute<System.ComponentModel.DescriptionAttribute>(source);
if (attr == null)
return null; return attr.Description;
} public static EnumT GetValueByDescription<EnumT>(string description)
{
var type = typeof(EnumT);
if (!type.IsEnum)
throw new ArgumentException("This method is destinated for enum types only.");
foreach (var enumName in Enum.GetNames(type))
{
var enumValue = Enum.Parse(type, enumName);
if (description == ((Enum)enumValue).GetDescription())
return (EnumType)enumValue;
}
throw new ArgumentException("There is no value with this description among specified enum type values.");
} }
}

使用方法:

Gender.Man.GetDescription()

注意MVC中特性的巧妙应用,改写!

C#秘密武器之特性的更多相关文章

  1. TypeScript: Angular 2 的秘密武器(译)

    本文整理自Dan Wahlin在ng-conf上的talk.原视频地址: https://www.youtube.com/watch?v=e3djIqAGqZo 开场白 开场白主要分为三部分: 感谢了 ...

  2. 第一章-第七题( 有人认为,“中文编程”, 是解决中国程序员编程效率一个秘密武器,请问它是一个 “银弹” 么? )--By 侯伟婷

    首先,“银弹”在百度百科中的解释是银色的子弹,我们更熟知的“银弹”一词,应该是在<人月神话>中提到的.银弹原本应该是指某种策略.技术或者技巧可以极大地提高程序员的生产力[1].此题目中关于 ...

  3. margin负值 – 一个秘密武器

    CSS盒模型中,margin是我们老熟悉的一个属性了, 它的负值你用过吗? 你知道 margin负值的秘密武器吗?我们一起看看吧! 1.带竖线分隔的横向列表(例如:网站底部栏目) 传统的分隔符是使用 ...

  4. C#秘密武器之扩展方法

    原文:C#秘密武器之扩展方法 为何要用扩展方法? 作为一个.NET程序猿,我们经常要跟.net自带类库或者第三方dll类库打交道,有时候我们未必能够通过反编译来查看它们的代码,但是我们通常需要给它们扩 ...

  5. 团队高效率协作开发的秘密武器-APIDOC

    团队高效率协作开发的秘密武器 1.前言 在团队协作开发中,不知道各位有没有遇到这样的问题: l 新人接手了项目代码,因没有项目文档,只能靠追踪路由,寻读代码分析业务逻辑 l 前端同学写好了页面,苦等后 ...

  6. 当3D打影人头”成为黑客的秘密武器,隐私该如何保护?

    在<碟中谍>系列电影中,除了超级敬业又帅气的阿汤哥之外,最让人津津乐道的桥段就是用3D打印做出来的"人头".通过这些惟妙惟肖的"人头",阿汤哥完成了 ...

  7. C#秘密武器之异步编程

    一.概述 1.什么是异步? 异步操作通常用于执行完成时间可能较长的任务,如打开大文件.连接远程计算机或查询数据库.异步操作在主应用程序线程以外的线程中执行.应用程序调用方法异步执行某个操作时,应用程序 ...

  8. C#秘密武器之反射——基础篇

    先来一段有用的反射代码 namespace Calculator { public interface Iwel { String Print(); } } namespace Calculator ...

  9. C#秘密武器之泛型

    一.简介: 很多初学者在刚开始接触泛型的时候会比较难理解泛型,在这里先把 “泛型”当作一个形容词,这样就方便理解了,因为很多东西都可以是泛型的!比如:“泛型的类”,“泛型的方法”,“泛型的接口”,“泛 ...

随机推荐

  1. Ubuntu Nginx

    如果是阿云的ECS服务器,默认是已经安装了Apache服务器的,但一般都用不到,可以选择将它卸载 sudo service apache2 stop update-rc.d -f apache2 re ...

  2. 论文笔记-RCNN

    CAFFE玩了也有段时间了,现在开始准备研究一下物体检测,现在知道的有RCNN.spp-net.Fast-RCNN和Faster-RCNN,作为菜鸟我还是从头学习,决定先看RCNN,因为有项目要做还要 ...

  3. PAT L3-001. 凑零钱

    $01$背包,路径记录,贪心. 可以将物品从大到小排序之后进行背包,同时记录路径. #include<map> #include<set> #include<ctime& ...

  4. zabbix主机自动发现

    环境说明 角色 主机名 IP zabbix-server c1.heboan.com 192.168.88.1 zabbix-agent c2.heboan.com 192.168.88.2 zabb ...

  5. Flask实战第56天:板块管理

    cms布局 编辑 cms_boards.html {% block main_content %} <div class="top-box"> <button c ...

  6. Python开发基础-Day24socket套接字基础2

    基于UDP的socket 面向无连接的不可靠数据传输,可以没有服务器端,只不过没有服务器端,发送的数据会被直接丢弃,并不能到达服务器端 #客户端 import socket ip_port=('127 ...

  7. [Codeforces #174] Tutorial

    Link: Codeforces #174 传送门 A: 求原根的个数,有一条性质是原根个数为$\phi(\phi(n))$,多了一个不会证的性质 如果要确定哪些是原根的话还是要枚举,不过对于每个数不 ...

  8. BZOJ 3450 Tyvj1952 Easy(期望)

    [题目链接] http://www.lydsy.com/JudgeOnline/problem.php?id=3450 [题目大意] 给出一个字符串,包含o,x和?,一个字符串的得分为 每段连续的o的 ...

  9. BZOJ 3544 [ONTAK2010]Creative Accounting(set)

    [题目链接] http://www.lydsy.com/JudgeOnline/problem.php?id=3544 [题目大意] 找一段区间使得Σai mod m的值最大. [题解] 首先计算前缀 ...

  10. 【推导】【贪心】Codeforces Round #431 (Div. 1) A. From Y to Y

    题意:让你构造一个只包含小写字母的可重集,每次可以取两个元素,将它们合并,合并的代价是这两个元素各自的从‘a’到‘z’出现的次数之积的和. 给你K,你构造的可重集必须满足将所有元素合而为一以后,所消耗 ...