C#中Attribute介绍

什么是特性?

  MSDN中定义为:公共语言运行时运行添加类似关键字的描述声明,叫做Attribute,它对程序中的元素进行标注,如类型、方法、字段和属性等。attribute和Microsoft.Net Framework文件的元数据保存在一起,可以用来在运行时描述你的代码,或者在程序运行时影响应用程序的行为

  我们简单地总结:定制特性attribute,本质上是一个类,其为目标元素提供关联附加信息,并在运行时以反射的方式来获取附件信息。

什么是属性?

  属性是面向对象编程的基本概念,提供了对私有字段的封装,C#中以get和set访问器方法实现对可读可写属性的操作,提供了安全和灵活的数据访问封装。

特性和属性的区别?

  在功能和应用上,二者其实没什么太多模糊的概念交叉,因此也没有必要放在一起比较。

attribute通用规则

  1.特性可以应用的目标元素包括:程序集(assemby)、模块(module)、类型(Type)、属性(Property)、事件(Event)、字段(Field)、方法(Method)、参数(param)、返回值(return).

  2.特性以[,]形式展示。放在紧挨着元素上

  3.attribute实例,是在编译期进行初始化,而不是运行期。

  .......

  示例如下:

  

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

namespace _01AttributeTest
{
    class Program
    {
        static void Main(string[] args)
        {
            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();

            Console.Read();
        }

        
    }

    public class Tester
    {
        [Test("Error here.")]
        public  void CannotRun()
        {

        }
    }

    [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. ");
        }
    }
}

参考:

https://msdn.microsoft.com/zh-cn/library/system.attribute(v=vs.110).aspx

《你必须知道的.Net》

posted @ 2016-06-23 22:41  齐_大圣  阅读(2756)  评论(0编辑  收藏  举报