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