简体   繁体   中英

Better way to manage getter/setter with Action on setter

I have an object that contains a public Action to call an update method within another class, whenever a property changes in the first class. It looks something like this:

public class FirstClass {

  public Action Update;

  private string _description;

  public string Description
  {
    get { return _description; }
    set
    {
        if (_description == value) return;
        _description = value;
        Update();
    }
  }
}

There are about 30 different properties that this needs to be applied to. Is there a more efficient way to accomplish this?

This looks like you want to use Aspect Oriented Programming (AOP). I currently use Postsharp ( http://www.postsharp.net ) to achieve this, but there are other alternatives too. The description below relates to Postsharp - other implementations may differ.

Create an interface that can provide the update action.

public interface IUpdateAction {
   public Action Update { get; }
}

then create an aspect, this is implemented as an attribute

[PSerializable] 
public class UpdateActionAttribute : LocationInterceptionAspect 
{ 

  public override void OnSetValue(LocationInterceptionArgs args) 
  { 
    if ( args.Value != args.GetCurrentValue() )
    {
      args.Value = args.Value;
      args.ProceedSetValue();
     ((IUpdateAction)args.Instance).Update();
    } 
  } 
}

Then you can apply the aspect to your class

public class FirstClass : IUpdateAction {

  public Action Update {get; set;}

  [UpdateAction]
  public string Description {get;set;}

}

When the code is compiled the rewriter will kick in and implement the aspect for the assigned properties.

You can take this further by using multicasting to apply it all properties or a filtered list.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM