Detect variable change c# [duplicate]

2020-07-30 01:25发布

I've been searching this for a while and I didn't found anything for my problem.

I have a integer:

private static int kills = 0;

I want a function to run when that variable changes. Like, it is 0 now. If it changes to 2, I want a function like OnVarChange that will be called, and that function OnVarChange will return the amount that was changed. In this case 2-0=2, so it will return 2.

Is this possible? How do I do it?

Hope you understand what I just said :p

3条回答
劫难
2楼-- · 2020-07-30 02:03

Make a property, which allows logic inside of it. That would be a good place to add this kind of functionality:

private static int kills = 0;

public static int Kills
{
    get
    {
        return kills;
    }
    set
    {
        this.kills = value;
        this.OnVarChange();
    }
}

A better option would be to implement INotifyPropertyChanged, which is an interface that UI and other parts of the framework can pick up and act on.

public class X : INotifyPropertyChanged
{
    private int kills = 0;

    public int Kills
    {
        get
        {
            return kills;
        }
        set
        {
            this.kills = value;
            this.OnPropertyChanged();
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;

    protected void OnPropertyChanged([System.Runtime.CompilerServices.CallerMemberName] string propertyName = "")
    {
        PropertyChangedEventHandler pc = this.PropertyChanged;

        if (pc != null)
        {
            pc(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}
查看更多
smile是对你的礼貌
3楼-- · 2020-07-30 02:15
static int Kills
{
 get{
return kills;
}
 set{
    OnVarChange(kills,value);
    kills = value;
}
}

Define a property for kills. Use this property to change value of kills. You can use set accessor of this property to call a method to detect change in variable kills.

查看更多
家丑人穷心不美
4楼-- · 2020-07-30 02:18

You need to provide a change mechanism:

Add:

public static int Kills{
    get{  return kills; }
    set{

        kills = value;
        //change code here...
       }
}

Only set using this public Kills property. Don't directly change the instance member kills if possible. But there is always an exception.

查看更多
登录 后发表回答