读你必须知道的.NET(三)

继续学习你必须知道的.NET:http://www.cnblogs.com/anytao/archive/2007/04/19/must_net_03.html

特性:定制特性attribute,本质上是一个直接或者间接继承自System.Attribute的类,为目标元素提供关联附加信息,并在运行期以反射的方式来获取附加信息,可应用的目标元素为:程序集、模块、类型、属性、事件、字段、方法、参数、返回值,主要用在序列化、编译器指令、设计模式方面,编译时初始化。C#允许以指定的前缀来表示特性所应用的目标元素,建议这样来处理,因为显式处理可以消除可能带来的二义性。

using System; 

namespace Anytao.net 
 {
     [assembly: MyAttribute(1)]          //应用于程序集
    [moduel: MyAttribute(2)]            //应用于模块
    pubic class Attribute_how2do
     {
         //TODO
    } 
 }

定制特性也可以用在其他定制特性上因为特性本身也是一个类,遵守类的公有规则,不影响应用元素的任何功能,只是约定了该元素具有的特质。所有非抽象特性必须具有public访问限制。

属性:面向对象编程的基本概念,提供了对私有字段的访问封装(get与set访问器方法实现对可读可写属性的操作,提供安全性和灵活性)。

定义特性:

[AttributeUsage(AttributeTargets.Class |
         AttributeTargets.Method,
         Inherited = true)]
     public class TestAttribute : System.Attribute
     {
         public TestAttribute(string message)
         {
             Console.WriteLine(message);
         }
         public void RunTest()
         {
             Console.WriteLine("TestAttribute here.");
         }
     }

应用于目标元素:

[Test("Error Here.")]
public void CannotRun()
{
   //TODO
}

使用反射机制获取元素附加信息:

public static void Main()
{
    Tester t = new Tester();
    t.CannotRun();

    Type tp = typeof(Tester);
    MethodInfo mInfo = tp.GetMethod("CannotRun");            
    TestAttribute myAtt = (TestAttribute)Attribute.GetCustomAttribute(mInfo, typeof(TestAttribute));
    myAtt.RunTest();
}

Attribute的本质在于以编程的方式为生成的Assembly添加Metadata,通过Reflection分析这些Metadata,来作出相应的操作。

原文地址:https://www.cnblogs.com/Ribbon/p/2935563.html