C#如果int值增加/增加了5或特定值,请采取措施

C#如果int值增加/增加了5或特定值,请采取措施,c#,C#,我想知道如果int值增加5或特定值,是否可以执行某些操作?如果是,如何做到 例如: int intExample = 0; if(intExample has incremented/increased by 5 or specific value) { doSomething(); } 只要它增加5或特定值,它就会调用doSomething()方法 提前谢谢 您可以将属性与EventMitters一起使用 private int _prop1; //#1 public event S

我想知道如果int值增加5或特定值,是否可以执行某些操作?如果是,如何做到

例如:

int intExample = 0;

if(intExample has incremented/increased by 5 or specific value) {

doSomething();

}
只要它增加5或特定值,它就会调用doSomething()方法


提前谢谢

您可以将属性与EventMitters一起使用

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();
    }
 }

使用字段将很困难,但是使用属性可以分别控制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;

当然感谢您的评论。你能举个例子吗?我一定会非常感激的!你对此做过研究吗?属性是一个非常基本的C#功能,可以用非常简单的方式实现。搜索属性和INotifyPropertyChanged。你想要的是一样的图案这正是我想要的!谢谢