Is there a way to do this:
class Example {
[ChangeNotification]
private int field;
}
Such that changing the value of "field" would automatically get logged, g开发者_如何学JAVAenerate an event, etc?
No, attributes are type specific, not instance specific.
But you can implement INotifyPropertyChanged
on all you objects and have some class listen to all the events and do the logging.
At first view, I would better recommend that you implement the INotifyPropertyChanged
interface, as an Attribute
is type specific.
You can do something similar (at least to a property, but not to a field) via Aspect oriented programming. However, this requires the use of a program like PostSharp, which actually rewrites the code inline based on the attribute.
Typically, this is used to implement INotifyPropertyChanged on a property. However, there are rewrite rules for logging and other features available.
This won't work for a field, however. It does work for a property, since the rewriter can add code to the property set method, but a field is handled directly by the CLR.
yes it's possible with postsharp using OnFieldAccessAspect http://www.sharpcrafters.com/forum/Topic2244-4-1.aspx
精彩评论