usingSystem;
namespaceConsoleApplication1
{
//定义枚举
[System.Flags()]
publicenumAccountsE
{
Saveings=0x0001,
Checking=0x0002,
Brokerage=0x0004
}
//自定义特性
[System.AttributeUsage(AttributeTargets.Class)]
publicclassAccountsAttribute:Attribute
{
publicAccountsEaccounts;
publicAccountsAttribute(AccountsEaccounts)
{
this.accounts=accounts;
}
}
[ConsoleApplication1.Accounts(AccountsE.Saveings)]
classChildAccount{}
[ConsoleApplication1.Accounts(AccountsE.Saveings|AccountsE.Checking|AccountsE.Brokerage)]
classAdultAccount{}
classClass1
{
[STAThread]
staticvoidMain(string[]args)
{
CanWriteCheck(newChildAccount());
CanWriteCheck(newAdultAccount());
CanWriteCheck(newClass1());
}
publicstaticvoidCanWriteCheck(objectobj)
{
//构造AccountsAttribute实例
AccountsAttributechecking=newAccountsAttribute(AccountsE.Checking);
//通过Attribute.GetCustomAttribute的静态方法来得到指定的特性的实例,然后就可以读取实例的属性了,用此来判断
//依据
AttributevalidAccounts=Attribute.GetCustomAttribute(obj.GetType(),typeof(AccountsAttribute),false);
if(validAccounts!=null)
{
AccountsAttributetmpAccounts=validAccountsasAccountsAttribute;
if((checking.accounts&tmpAccounts.accounts)==checking.accounts)
{
Console.WriteLine("{0}typescanwritechecks.",obj.GetType());
}
else
{
Console.WriteLine("{0}typecannotwritechecks.",obj.GetType());
}
}
else
{
Console.WriteLine("{0}typecannotwritechecks.",obj.GetType());
}
}
}
}