开发者

C# Custom Setter Event or Inherited Setter

Is there a way in C# to have a setter inherit from "something" that would allow me to run some code each time a setter is invoked for a particular base class and it's inheritors?

What I want to do is have a boolean flag on my base class called IsValid. I will set this boolean to true after validati开发者_JS百科ng an object, then if any setter is invoked after validation, I want the setter to change the IsValid flag to false.

I don't want to have to write this logic into every setter.


No, this isn't directly possible in the language.

However, one way to handle this is to using something like INotifyPropertyChanged. If your base class specifies that it implements this interface, your subclasses should also raise PropertyChanged events. The base class could use this to track changes and validate the object.


You are basically asking for some version of Aspect Oriented Programming (AOP). You have a common operation that you want to perform across all properties, without implementing it in every case.

I'm not sure what the choices really are for AOP in C#, but one I have used before is Spring.Net AOP. What it will do is wrap your class in a dynamically created wrapper which will intercept all calls to your properties and then allow you to implement some common logic to execute.


Take a look at the PostSharp to add this functionality or maybe this thread at StructureMap http://groups.google.com/group/structuremap-users/browse_thread/thread/fbadf4c2779ab8ed?hl=en


If the properties in question are virtual, you can override them to provide the notification and call the base class' implementation to ensure the "set" goes through.


The only way of doing this in C# without code in every setter is through a TransparentProxy. It is a bit cumbersome, but it can be made to appear invisible to the coder.


Well, what you could do is create a virtual method in the abstract class and call it from the property setter. Then you can override it in the inherited classes.


I run into this issue all the time... so i use a pattern like this:

public class Foo
{
   public string Bar1
   {
      get{return this._Bar1;}
      set{this.SafeSet(ref this._Bar1, value);}
   }public string _Bar1;

   public int Bar2
   {
      get{return this._Bar2;}
      set{this.SafeSet(ref this._Bar2, value);}
   }public int _Bar2;

   protected virtual SafeSet<T> (ref T local, T val)
   {
      if(local != val)
      {
         local = val;
         //whatever other post-processing you want
      }
   }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜