自定义属性类实例的比较,默认的Attribute.Match 只是简单的调用了Equal方法,我们可以重写此Match方法来精确定义对Attribute的比较。
代码:
自定义属性类:
代码
[AttributeUsage(AttributeTargets.Class)]
internal class AccountsAttribute : System.Attribute
{
private EnumAccounts m_accounts;
public AccountsAttribute(EnumAccounts accounts)
{
this.m_accounts = accounts;
}
public override bool Match(object obj)
{
//if the base type is not System.Attribute
//it is a Customer Attribute inhreit from System.Attribute
//the next line should not be annotate
//return base.Match(obj);
if (obj == null)
return false;
if (this.GetType() != obj.GetType())
return false;
AccountsAttribute other = (AccountsAttribute)obj;
if ((other.m_accounts & this.m_accounts) != this.m_accounts)
return false;
return true;
}
public override bool Equals(object obj)
{
//return base.Equals(obj);
if (obj == null)
return false;
if (this.GetType() != obj.GetType())
return false;
AccountsAttribute other = (AccountsAttribute)obj;
if (other.m_accounts != this.m_accounts)
return false;
return true;
}
public override int GetHashCode()
{
//return base.GetHashCode();
return (Int32)m_accounts;
}
}
目标类:
代码
[Accounts(EnumAccounts.Savings)]
internal sealed class ChildAccount
{
}
[Accounts(EnumAccounts.Savings | EnumAccounts.Brokerage | EnumAccounts.Checking)]
internal sealed class AdultAccount
{
}
调用:
代码
public class AccountsAdapter
{
private static void CanWriteCheck(object obj)
{
Attribute checking = new AccountsAttribute(EnumAccounts.Checking);
Attribute validAccounts = Attribute.GetCustomAttribute(obj.GetType(), typeof(AccountsAttribute), false);
if ((validAccounts != null) && checking.Match(validAccounts))
{
Console.WriteLine("{0} types can write checks.", obj.GetType());
}
else
{
Console.WriteLine("{0} types can not write checks.", obj.GetType());
}
}
public static void AttributeMatch()
{
CanWriteCheck(new ChildAccount());
CanWriteCheck(new AdultAccount());
CanWriteCheck(new AccountsAdapter());
}
}