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());
   }

  }
 }
}
posted @ 2006-08-08 16:53  吴东雷  阅读(1345)  评论(0编辑  收藏  举报