C#自定義Attribute舉例!

using System;

namespace ConsoleApplication1
{
 //定義枚舉
 [System.Flags()]
 public enum AccountsE
 {
  Saveings=0x0001,
  Checking=0x0002,
  Brokerage=0x0004
 }
 //自定義特性
 [System.AttributeUsage(AttributeTargets.Class)]
 public class AccountsAttribute:Attribute
 {
  public AccountsE accounts;
  public AccountsAttribute(AccountsE accounts)
  {
   this.accounts=accounts;
  }
 }
 [ConsoleApplication1.Accounts(AccountsE.Saveings)]
 class ChildAccount{}
 [ConsoleApplication1.Accounts(AccountsE.Saveings|AccountsE.Checking|AccountsE.Brokerage)]
 class AdultAccount{}

 class Class1
 {
  [STAThread]
  static void Main(string[] args)
  {
   CanWriteCheck(new ChildAccount());
   CanWriteCheck(new AdultAccount());
   CanWriteCheck(new Class1());
  }
  public static void CanWriteCheck(object obj)
  {
   //構造AccountsAttribute實例
   AccountsAttribute checking=new AccountsAttribute(AccountsE.Checking);
   //通過Attribute.GetCustomAttribute的靜態方法來得到指定的特性的實例,然後就可以讀取實例的屬性了,用此來判斷
   //依據
   Attribute validAccounts=Attribute.GetCustomAttribute(obj.GetType(),typeof(AccountsAttribute),false);
   if (validAccounts!=null)
   {
    AccountsAttribute tmpAccounts=validAccounts as AccountsAttribute;
    if((checking.accounts & tmpAccounts.accounts)==checking.accounts)
    {
     Console.WriteLine("{0} types can write checks.",obj.GetType());
    }
    else
    {
     Console.WriteLine("{0} type can not write checks.",obj.GetType());
    }
   }
   else
   {
    Console.WriteLine("{0} type can not write checks.",obj.GetType());
   }

  }
 }
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章