开发者

How to write a Trigger?

I want my C# code to call an event whenever a value is assigned to my object.

How exactly would I need to go about that?

class MyClass {

  ManualResetEvent mre;

  public MyClass() {
    mre = new ManualResetEvent(false);
    Data = null;
  }

  public object Data { get; set; }

  void DataSet(object sender, EventArgs e) {
    Console.WriteLine("object Data has been set.");
    mre.Set();
  }

}

Delegates don't开发者_JAVA技巧 seem to be what I need. An event, maybe? How would I write such an event, if so?

MyClass mc;

void processA() {
  mc = new MyClass();
  mc.Data = GetDataFromLongProcess();
}


private object data;
public object Data {
    get { return data;}
    set {
        if(value != data) {
            data = value;
            OnDataChanged();
        }
    }
}
protected virtual void OnDataChanged() {
    EventHandler handler = DataChanged;
    if(handler != null) handler(this, EventArgs.Empty);
}
public event EventHandler DataChanged;

then hook any code to the DataChanged event. For example:

MyClass mc = ...
mc.DataChanged += delegate {
    Console.WriteLine("new data! wow!");
};


If you want to fire an event when your property is set, you would do something like this:

 public event Action OnDataChanged;

 protected object _data = null;
 public object Data
 {
     get { return _data; }
     set
     {
         _data = value;
         if(OnDataChanged != null)
            OnDataChanged();
     }
 }

Then you would simply wire up event handlers to your object like so:

 mc = new MyClass();
 mc.OnDataChanged += delegate() { Console.WriteLine("It changed!"); };
 mc.Data = SomeValue();


I think you're on the right track with an event-based model. Also take a look at the Observer pattern (which is the basis for .Net delegates and events underneath it all, as I understand):

http://www.dofactory.com/Patterns/PatternObserver.aspx

But the bottom line, as the other useful answer so far (Mr. Gravell's implementation) indicates, you're going to have to have code IN the setter to get it hooked up. The only alternative would be to poll the value for changes, which just smells bad to me.


you could implement INotifyPropertyChanged (this is more or less a event) or you could take your class a Action (Trigger) and call this, whenn the property changed.

Just don't use automatic properties but a concrete setter and call your event/trigger from there.


Conceptually, you would define an event in your class, and in your property set blocks, you would invoke the event with the necessary arguments to determine what just happened.


 public event SomeDelegateThatTakesIntAsParameter myEvent;
 void SetData(int data)
 {
   if(myEvent!= null)
     myEvent(data)
 }
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜