.NET Attribute(特性)的作用與用法——幾句話解決Attribute使用的困惑


      本小文旨在言簡意賅的介紹.NET中Attribute(特性)的作用與使用,算是對Attribute學習的一個總結吧,不當之處煩請熱心網友幫忙斧正,不勝感激!切入正題。

一點說明

只介紹作用與使用方法,不深究原理。[其原理可參考MSDN:http://msdn.microsoft.com/en-us/library/aa288454(v=vs.71).aspx 等相關文章]

什么是Attribute?

Attribute不是別的東西,就是類(貌似廢話)。確切的說,它是為C#代碼(類型、方法、屬性等)提供描述性信息的類!

Attribute作用是什么?

兩點感觸:

  1. 修飾C#代碼,對其進行描述或聲明;
  2. 運行時通過反射來獲取並使用其聲明或控制信息。[不是供一般意義上調用或使用的]

怎么使用Attribute?

四點感觸:

  1. 自定義特性:所有的自定義特性必須直接或間接繼承Attribute基類,示例:
    class TestAttribute : Attribute

     

  2. 實例化:但不是常規意義上的用new實例化它,而是用成對兒的方括號”[”和”]”,示例:
    [Test(Ignore = false)]

     

  3. 使用位置:必須放在緊挨着被修飾對象的前面。示例:
    [Test(Ignore = false)]
    public static void TestMethod()

     

  4. 賦值方式:構造函數的參數和類的屬性都在括號內賦值,且構造函數實參必須在屬性前面。            

使用小例

[說明:該示例通過自定義特性TestAttribute來控制(或說明)TestMethod方法是否執行,Ignore=false則執行,else則忽略]     

View Code
namespace TestApp
{
    class Program
    {
        static void Main(string[] args)
        {
            MemberInfo info = typeof(Program).GetMethod("TestMethod");
            TestAttribute attr = (TestAttribute)Attribute.GetCustomAttribute(info, typeof(TestAttribute));
            if (attr != null)
            {
                if (attr.Ignore)
                {
                    Console.WriteLine("TestMethod should be ignored. ");
                }
                else
                {
                    Console.WriteLine("TestMethod can be executed/invoked. ");
                    TestMethod();
                }
            }

            Console.Read();
        }

        [Test(Ignore = false)]
        public static void TestMethod()
        {
            Console.WriteLine("Message comes from TestMethod.");
        }
    }

    class TestAttribute : Attribute
    {
        public TestAttribute()
        {
        }

        public bool Ignore { get; set; }
    }
}

運行結果

Ignore=true

Ignore=false

篇后語

這個小例子看似沒有任何實用意義,但是在實際應用中對於一類特性,用Attribute的方式來控制是很方便也很容易擴展和維護的,比如我們最常用的Seriablizable、ServiceContract等。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM