Can a custom attribute query the value of the property it's attached to?
Example:
[OnlyShowIfValueIsNonZero]
public int Foo { get开发者_StackOverflow; set; }
In the code for OnlyShowIfValueIsNonZero
, I need to be able to query the value of Foo
. Is this possible? If yes, how?
An attribute is not aware of the member it is assigned to, and for an attribute an instance will only be created if you access it via reflection. You cannot let an attribute interact with code directly - there are some frameworks like PostSharp though that inject code at compile time using attributes.
You can however from reflection supply the member it is assigned to, and since you already need the member to access its attributes, you could create a method in that attribute that accepts the member as parameter.
I think you're starting to get into the world of aspect orientated programming here. Many AOP frameworks provide extensibility points to define your own custom aspects - which is what I think would suit you.
PostSharp is a very popular AOP framework for .NET
maybe , it is like this. and for example , T is your class...
foreach (PropertyInfo propertyInfo in (typeof(T)).GetProperties()){
foreach (object attribute in propertyInfo.GetCustomAttributes(true))
{
if ( attribute is OnlyShowIfValueIsNonZero )
{
......
}
}
}
精彩评论