I want to react, whenever an integer value has changed. So, is there a possibility to write an own eventhandler? I need to get the old value and the new one, because I have to de-reference some events for an object in a list with the index of the old value and reference these events to the listitem with the index of the new value.
Something like this (really abstract):
value.Changed += new Eventhandler(valuechanged);
private void valuechanged(object sender, eventargs e)
{
list[e.Oldvalue] -= some eventhandler;
list[e.newValue] += some eventhanlder;
}
Thanks.
You can do something like this:
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<ValueChangedEventArgs> 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));
}
}
}
So you can use your class like here ( 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());
}
This will print:
Last Value: 10
New Value: 100
Last Value: 100
New Value: 1000
Last Value: 1000
New Value: 2000
The only things that comes close is the INotifyPropertyChanged
and INotifyPropertyChanging
interfaces. These define the PropertyChanged
& PropertyChanging
events respectively.
However, these won't give you the new or old value, just that it has changed/changing.
You typically define them on properties.. ala:
private int _myInt;
public int MyInt
{
get
{
return this._myInt;
}
set
{
if(_myInt == value)
return;
NotifyPropertyChanging("MyInt");
this._myInt = value;
NotifyPropertyChanged("MyInt");
}
}
}
Note: NotifyPropertyChanging()
& NotifyPropertyChanged()
are just private methods that invoke the events.
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.