如何在 C# 中使用 Attribute

譯Attribute 在 C# 中是一個很是強大的特性,它可以給你的程序集添加元數據信息。

Attribute 其實是一個對象,它能夠與如下元素中的任何一個相關聯: 程序集、類、方法、委託、枚舉、事件、字段、接口、屬性和結構,它會在這些對象上作信息聲明,當程序運行以後,你能夠經過反射來獲取關聯到這些對象上的 Attribute 信息,換句話說:你能夠經過 Atrribute 向程序集註入一些額外信息,而後在運行時經過反射來獲取,attribute 通常由 名字 + 一些可選參數 構成, attribute 名字對應着 atrribute 類。框架

你能夠利用 attribute 去校驗你的業務model的正確性, attribute 有兩種:內置 + 自定義, 前者是 .net framework 框架的組成部分,後者須要經過繼承 System.Attribute 類來實現自定義。ide

如今來看看代碼怎麼寫,Obsolete 特性用來標記一個方法是過期的,這個過期的意思是:你不該該再使用這個方法了,將來框架也會將其剔除,目前也存在其替代方案。其實在第三方框架中有不少這樣的例子,下面的代碼片斷展現瞭如何在方法頂部使用 Obsolete 特性。函數

[Obsolete("This method is obsolete...")]
public static void DoSomeWork()
{
}

若是你在程序中調用了這個方法,當你編譯代碼時,在 Visual Studio 輸出窗口中會如今一些警告信息,以下圖:this

固然,若是你必定要忽視它也是能夠的,如今,假如你但願你的開發同事不容許調用這個方法,那如何去限定呢?哈哈,能夠使用 Obsolete 的第二個參數,這個參數是可選的,下面是 DoSomeWork()  方法的修改版本,請注意這是一個 Boolean 型參數。.net

[Obsolete("This method is obsolete...", true)]
 public static void DoSomeWork()
 {

 }

當把 true 給了這個可選參數後,再次編譯代碼,你會發現代碼根本編譯不經過,是否是完美的解決了你的問題,是吧! 截圖以下:對象

自定義 attribute

這一小節咱們來看一下如何去實現自定義的 attribute,要想自定義實現,能夠建立一個類並繼承 System.Attribute 類便可,以下代碼所示:blog

using System;
public class CustomAttribute : Attribute
{

}

要想限定 CustomAttribute 的使用,能夠用 AttributeUsage 類去標記,這個類包含了以下屬性: ValidOn,AllowMultiple,Inherited 等等,這些標記均可以限定 CustomAttribute 的使用。繼承

下面的代碼片斷展現了 CustomAttribute 的修改版本,這個類使用構造函數去給內部的私有 string 賦值,代碼僅僅用於演示目的。接口

[AttributeUsage(AttributeTargets.All)]
    public class CustomAttribute : Attribute
    {
        private string text;
        public CustomAttribute(string text)
        {
            this.Text = text;
        }

        public string Text { get => text; set => text = value; }
    }

固然你也能夠按需去指定這些 AttributeTargets,以下代碼所示:事件

[AttributeUsage(AttributeTargets.Class |
    AttributeTargets.Constructor |
    AttributeTargets.Field |
    AttributeTargets.Method |
    AttributeTargets.Property,
    AllowMultiple = true)]
    public class CustomAttribute : Attribute
    {
        private string text;
        public CustomAttribute(string text)
        {
            this.Text = text;
        }

        public string Text { get => text; set => text = value; }
    }

接下來你能夠用反射來獲取應用到對象上的全部attributes,代碼以下:

static void Main(string[] args)
        {
            MemberInfo memberInfo = typeof(CustomAttribute);
            object[] attributes = memberInfo.GetCustomAttributes(true);
            for (int i = 0, j = attributes.Length; i < j; i++)
            {
                Console.WriteLine(attributes[i]);
            }
        }

接下來我準備將 CustomAttribute 類應用到 下面的 SomeClass 類上。

[CustomAttribute("Hello World...")]
public class SomeClass
{
}

能夠着重看下 CustomAttribute 是如何安插在 SomeClass 上的,並且我還傳遞了一個 Hello World... 字符串給它,下面的代碼展現瞭如何將 CustomAttribute 中的 Text 屬性打印出來。

class Program
    {
       static void Main(string[] args)
        {
            MemberInfo memberInfo = typeof(SomeClass);
            object[] attributes = memberInfo.GetCustomAttributes(true);

            foreach (object attribute in attributes)
            {
                CustomAttribute customAttribute = attribute as CustomAttribute;

                if (customAttribute != null)
                    Console.WriteLine("Text = {0}", customAttribute.Text);
                else
                    Console.WriteLine();
            }
        }
    }

    [CustomAttribute("Hello World...")]
    public class SomeClass
    {
    }
    

    [AttributeUsage(AttributeTargets.Class |
    AttributeTargets.Constructor |
    AttributeTargets.Field |
    AttributeTargets.Method |
    AttributeTargets.Property,
    AllowMultiple = true)]
    public class CustomAttribute : Attribute
    {
        private string text;
        public CustomAttribute(string text)
        {
            this.Text = text;
        }

        public string Text { get => text; set => text = value; }
    }

相關文章
相關標籤/搜索