价值改变了事件处理程序
每当整数值发生变化时,我想做出反应。 那么,是否有可能编写自己的事件处理程序? 我需要获取旧值和新值,因为我必须使用旧值的索引为列表中的对象取消引用某些事件,并使用新值的索引将这些事件引用到listitem。
像这样的东西(非常抽象):
value.Changed += new Eventhandler(valuechanged); private void valuechanged(object sender, eventargs e) { list[e.Oldvalue] -= some eventhandler; list[e.newValue] += some eventhanlder; }
谢谢。
你可以这样做:
class ValueChangedEventArgs : EventArgs { public readonly int LastValue; public readonly int NewValue; public ValueChangedEventArgs(int LastValue, int NewValue) { this.LastValue = LastValue; this.NewValue = NewValue; } } class Values { public Values(int InitialValue) { _value = InitialValue; } public event EventHandler ValueChanged; protected virtual void OnValueChanged(ValueChangedEventArgs e) { if(ValueChanged != null) ValueChanged(this, e); } private int _value; public int Value { get { return _value; } set { int oldValue = _value; _value = value; OnValueChanged(new ValueChangedEventArgs(oldValue, _value)); } } }
所以你可以像这里一样使用你的类( Console Test ):
void Main() { Values test = new Values(10); test.ValueChanged += _ValueChanged; test.Value = 100; test.Value = 1000; test.Value = 2000; } void _ValueChanged(object sender, ValueChangedEventArgs e) { Console.WriteLine(e.LastValue.ToString()); Console.WriteLine(e.NewValue.ToString()); }
这将打印:
Last Value: 10 New Value: 100 Last Value: 100 New Value: 1000 Last Value: 1000 New Value: 2000
唯一接近的是INotifyPropertyChanged
和INotifyPropertyChanging
接口。 它们分别定义了PropertyChanged
和PropertyChanging
事件。
但是,这些不会给你新的或旧的价值,只是它已经改变/改变。
您通常在属性上定义它们.ala:
private int _myInt; public int MyInt { get { return this._myInt; } set { if(_myInt == value) return; NotifyPropertyChanging("MyInt"); this._myInt = value; NotifyPropertyChanged("MyInt"); } } }
注意: NotifyPropertyChanging()
和NotifyPropertyChanged()
只是调用事件的私有方法。