C#特性(Attribute)入門(二)

字號:

定義或控制特性的使用
    AttributeUsage類是另外一個預(yù)定義特性類,它幫助我們控制我們自己的定制特性的使用。它描述了一個定制特性如和被使用。
    AttributeUsage有三個屬性,我們可以把它放置在定制屬性前面。第一個屬性是:
    ValidOn
    通過這個屬性,我們能夠定義定制特性應(yīng)該在何種程序?qū)嶓w前放置。一個屬性可以被放置的所有程序?qū)嶓w在AttributeTargets enumerator中列出。通過OR操作我們可以把若干個AttributeTargets值組合起來。
    AllowMultiple
    這個屬性標記了我們的定制特性能否被重復(fù)放置在同一個程序?qū)嶓w前多次。
    Inherited
    我們可以使用這個屬性來控制定制特性的繼承規(guī)則。它標記了我們的特性能否被繼承。
    下面讓我們來做一些實際的東西。我們將會在剛才的Help特性前放置AttributeUsage特性以期待在它的幫助下控制Help特性的使用。
    using System;
    [AttributeUsage(AttributeTargets.Class), AllowMultiple = false,
    Inherited = false ]
    public class HelpAttribute : Attribute
    {
    public HelpAttribute(String Description_in)
    {
    this.description = Description_in;
    }
    protected String description;
    public String Description
    {
    get
    {
    return this.description;
    }
    }
    }
    先讓我們來看一下AttributeTargets.Class。它規(guī)定了Help特性只能被放在class的前面。這也就意味著下面的代碼將會產(chǎn)生錯誤:
    [Help("this is a do-nothing class")]
    public class AnyClass
    {
    [Help("this is a do-nothing method")] //error
    public void AnyMethod()
    {
    }
    }
    編譯器報告錯誤如下:
    AnyClass.cs: Attribute Help is not valid on this declaration type.
    It is valid on class declarations only.
    我們可以使用AttributeTargets.All來允許Help特性被放置在任何程序?qū)嶓w前。可能的值是:
    Assembly,
    Module,
    Class,
    Struct,
    Enum,
    Constructor,
    Method,
    Property,
    Field,
    Event,
    Interface,
    Parameter,
    Delegate,
    All = Assembly | Module | Class | Struct | Enum | Constructor | Method | Property | Field | Event | Interface | Parameter | Delegate,
    ClassMembers = Class | Struct | Enum | Constructor | Method | Property | Field | Event | Delegate | Interface )