你可以做這樣的事情:
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));
}
}
}
所以,你可以使用你的類像這裏(控制檯測試):
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
可能的重複:http://stackoverflow.com/questions/7677854/notifypropertychanged-event-where-event-args-c是否可以覆蓋/添加一些代碼到int-class? – 2012-04-01 12:51:59