黑马程序员-.NET基础之特性

来源:互联网 发布:ubuntu和优麒麟哪个好 编辑:程序博客网 时间:2024/06/06 00:27

------- Windows Phone 7手机开发、.Net培训、期待与您交流! -------

 

一、特性概述

C#语言可以创建直接或间接派生于抽象类System.Attribute的类,称之为特性(Attribute)类。
一个关于特性类的声明定义一种新特性,特性可以被放置在其他声明上,即附加到各种程序实体(包括类型、方法、属性等),以添加元数据信息,如编译器指令或数据描述。特性主要为编译器提供额外的信息,编译器可以通过这些附加特性,自动生成相应的代码,从而实现特定的功能。程序代码也可以通过反射技术,在运行时环境中检索这些特性信息,以实现特定的操作。
C#语言包括下列2种形式的特性:
公共语言运行库(CLR)中预定义的特性
自定义特性,用于向代码中添加附加信息,该信息能够以编程方式检索
特性类可以具有定位参数(positional parameter)和命名参数(named parameter)列表

 

二、特性的使用

    将特性附加到程序实体的语法为:将括在方括号中的特性名置于其适用的实体声明之前。例如,C#外部方法的声明需要通过DllImport 特性以引用由DLL(动态链接库)实现的外部函数。根据约定,所有特性类都以单词“Attribute”结束,以区分于其它类。但是,在代码中,可以省略特性后缀“Attribute”

 

三、预定义通用特性类

    ConditionalAttribute类,ObsoleteAttribute类,AttributeUsageAttribute类,全局特性。下面给出预定义通用特性类ConditionalAttribute使用示例。

using System;using System.Diagnostics;namespace CSharpPractice.Attribute{    public class Trace    {        [Conditional("DEBUG")]        public static void Msg(string msg)        {            Console.WriteLine(msg);        }        [Conditional("DEBUG"), Conditional("TRACE")]        public static void Method2()        {            Console.WriteLine("DEBUG or TRACE is defined");        }    }    public class ProgramClass    {        static void Main()        {            Trace.Msg("Now in Main...");            Trace.Method2();            Console.WriteLine("Main Done.");            Console.ReadLine();        }    }}

 

 

四、自定义特性类

    通过直接或间接地从System.Attribute类派生,可以创建自定义特性类。特性类直接或间接地从 Attribute 派生,有助于方便快捷地在元数据中标识特性定义。
特性类的声明遵循下列规则:
派生类的类名一般采用XXXAttribute的命名规范,类名就是特性名。
构造函数的参数是自定义特性的定位参数。
任何公共读写字段或属性都是命名参数。
使用AttributeUsage特性指定特性类的限制条件

namespace CSharpPractice.Attribute{    [System.AttributeUsage(System.AttributeTargets.Class |                           System.AttributeTargets.Struct,                           AllowMultiple = true)  // 允许单个实体应用多次该属性    ]    public class AuthorAttribute : System.Attribute    {        private string name;        public double version;        public AuthorAttribute(string name)        {            this.name = name;            version = 1.0;        }    }    [Author("H. Ackerman", version = 1.1)]    [Author("M. Knott", version = 1.2)]    class SampleClass    {    // H. Ackerman's code goes here...        // M. Knott's code goes here...        public static void Main()        {            System.Console.WriteLine("Hello!");            System.Console.ReadLine();        }    }}


 

五、使用反射访问特性

    C#通过反射技术来检索用自定义特性定义的信息。首先通过GetType方法或者typeof关键字来获取类型;然后通过GetCustomAttributes方法获取所应用的自定义特性的对象数组;最后通过自定义特性的对象数组进行相应的操作处理。下面给出通过反射技术检索用自定义特性定义的信息示例。

namespace CSharpPractice.Attribute{    [System.AttributeUsage(System.AttributeTargets.Class |                         System.AttributeTargets.Struct,                         AllowMultiple = true)  // 允许单个实体应用多次该特性    ]    public class AuthorAttribute : System.Attribute    {        string name;           // 作者姓名        public double version;   // 版本        public AuthorAttribute(string name)        {            this.name = name;   // 设置作者姓名            version = 1.0;      // 默认版本值        }        public string GetName()        {   // 获取作者姓名信息            return name;        }    }    [Author("H. Ackerman")]    class FirstClass    {        // ...    }    // 无作者特性    class SecondClass    {        // ...    }    [Author("H. Ackerman"), Author("M. Knott", version = 2.0)]    class ThirdClass    {        // ...    }    class TestAuthorAttribute    {        static void Main()        {  // 打印3位作者的信息            PrintAuthorInfo(typeof(FirstClass));            PrintAuthorInfo(typeof(SecondClass));            PrintAuthorInfo(typeof(ThirdClass));            System.Console.ReadLine();        }        private static void PrintAuthorInfo(System.Type t)        {            System.Console.WriteLine("{0} 的作者信息:", t);            System.Attribute[] attrs = System.Attribute.GetCustomAttributes(t);  // 反射技术            foreach (System.Attribute attr in attrs)            {                if (attr is Author)                {                    Author a = (Author)attr;                    System.Console.WriteLine("   {0}, 版本 {1:f}", a.GetName(), a.version);                }            }            System.Console.ReadLine();        }    }}

 

------- Windows Phone 7手机开发、.Net培训、期待与您交流! -------

0 0
原创粉丝点击