是否想知道int值增加5或特定值是否可以做些什么?如果是这样,怎么办?
例如:
int intExample = 0;
if(intExample has incremented/increased by 5 or specific value) {
doSomething();
}
只要增加5或特定值,它就会调用doSomething()方法。
谢谢!
答案 0 :(得分:1)
使用字段将很困难,但是使用属性可以分别控制getter和setter并可以在事件发生之前对其进行处理。这是一个差异为5且特定值为99的示例。
public class Foo
{
private int intExample = 0;
public int IntExample
{
get { return intExample ; }
set
{
// if the value trying to be set is 5 lower or higher or is 99 call the method
if((value == intExample - 5) ||
(value == intExample + 5) ||
(value == 99))
{
DoSomething();
}
// set the value in the private field
intExample = value;
}
}
private void DoSomething()
{
// do something here
}
}
以及使用方法的示例是
// create the class
Foo foo = new Foo();
// set value of 32, this will change it but will not trigger as the default is 0 and is not 5 higher or lower or value of 99
foo.IntExample = 32;
// this will trigger as it's 5 more
foor.IntExample = 37;
答案 1 :(得分:0)
您可以将属性与EventEmmitters一起使用
private int _prop1;
//#1
public event System.EventHandler PropertyChanged;
//#2
protected virtual void OnPropertyChanged()
{
if (PropertyChanged != null) PropertyChanged(this,EventArgs.Empty);
}
public int Prop1
{
get
{
return _prop1;
}
set
{
//#3
_prop1=value;
OnPropertyChanged();
}
}