.NET:Attribute 入门(内训教程)

背景

接触过的语言中,C#(.NET 平台的多数语言都支持)、Java 和 Python 都支持这个特性,本文重点介绍 C# 中的应用,这里简单的对 C#、java 和 Python 中的 Attribute 做个总结:

  • C#:可以封装状态和行为,会作为元数据存储在程序集中,会关联某些语言结构,可以运行时读取。
  • Java:只能封装状态(Java 中叫:Annotation),会作为元数据存储在程序集中,会关联某些语言结构,可以运行时读取(根据配置,某些 Annotation 只在存在编译时)。
  • Python:只是语言糖,算是一种工厂(Python 中叫 Detector),比如:装饰一个对象,然后返回一个代理。

后面谈到 Attribute 都是指 C# 中的 Attribute。

认识 Attribute

Attribute 是一种类型,这种类型封装了一些元数据(状态)和行为,Attribute 可以应用在某些级别的语言结构上(程序集、类、方法、参数等等),Attribute 有如下用处:

  1. 影响编译器:
    1     [CLSCompliant]
    2     class Program
    3     {
    4         static void Main(string[] args)
    5         {
    6         }
    7     }

    注意:除了编译器开发团队可以开发这种 Attribute,其他人是不可能开发的。

  2. 影响运行时:
    1     [MTAThread]
    2     class Program
    3     {
    4         static void Main(string[] args)
    5         {
    6         }
    7     }

    注意:除了 CLR 开发团队可以开发这种 Attribute,其他人是不可能开发的,当然,如果 CLR 提供了一种机制,可以识别某个 Attribute 的子类的话,你也可以继承这个 Attribute 开发自己的子类了。

  3. 影响框架和应用程序:
     1 using System;
     2 using System.Collections.Generic;
     3 using System.Linq;
     4 using System.Text;
     5 using System.Threading.Tasks;
     6 using System.Web.Mvc;
     7 
     8 using Common.Logging;
     9 using Happy.ExceptionHanding;
    10 using Happy.Web.Mvc.Newtonsoft;
    11 
    12 namespace Happy.Web.Mvc.ExceptionHanding
    13 {
    14     /// <summary>
    15     /// 处理应用程序未捕获的异常。
    16     /// </summary>
    17     [AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = true)]
    18     public class WriteExceptionResultAttribute : FilterAttribute, IExceptionFilter
    19     {
    20         /// <inheritdoc />
    21         public void OnException(ExceptionContext filterContext)
    22         {
    23             var exception = filterContext.Exception;
    24             if (!FriendlyExceptionRegistry.IsFriendly(exception.GetType()))
    25             {
    26                 LogManager.GetCurrentClassLogger().Error(exception);
    27             }
    28             filterContext.Result = CreateErrorResult(exception);
    29             filterContext.ExceptionHandled = true;
    30         }
    31 
    32         private static ActionResult CreateErrorResult(Exception exception)
    33         {
    34             var information = ExceptionInformationProviderRegistry.CreateInformation(exception);
    35 
    36             return new NewtonsoftJsonResult
    37             {
    38                 Data = information
    39             };
    40         }
    41     }
    42 }

    注意:之所以可以开发这个 Attribute,是因为 ASP.NET MVC 提供了这种机制,它的内部实现会在运行时反射这种(实现了某个基类)Attribute,然后根据 Attribute 的元数据执行某些逻辑,或者调用 Attribute 的行为。

开发自定义 Attribute

参考文章:http://www.cnblogs.com/hyddd/archive/2009/07/20/1526777.html

 

posted on 2014-01-23 17:32  幸福框架  阅读(1697)  评论(0编辑  收藏  举报

导航

我要啦免费统计