简体   繁体   中英

On variable value change.

I have some code which sets a variable depending on different inputvalues. Simplified here:

if (hipDepthPoint.X < 100)
{
    Xvariabel = 1;
}
else 
{
    Xvariabel = 2;
}

Then I want to look for changes in the variable Xvariabel , and whenever the value changes I want to perform an action. I have looked into events and properties, but I couldnt make any of them work.

Try to do it with a property

if (hipDepthPoint.X < 100)
{
    Xvariabel = 1;
}
else 
{
    Xvariabel = 2;
}


public int Xvariabel 
{
    get { return _xvariabel ; }
    set
    {
        if (_xvariabel != value)
        {
            _xvariabel = value
            //do some action
        }
    }
}

Properties with setter should do the work.
you should write something like that:

private int _X     
public int X {
    get { return _X ; }
    set { _X  = value; //Your function here }
}

Here is an example what you can do using an invention and power of .net. I used INotifyPropertyChange, but you can use your own interface. This is very universal type, that will notify its own value change to multiple listeners

public class Test
{
    public static void Main(string[] args)
    {
        ObservableVar<int> five = new ObservableVar<int>(5);
        five.PropertyChanged += VarChangedEventHanler;
        five.Value = 6;
        int six = five;
        if (five == six)
        {
            Console.WriteLine("You can use it almost like regular type!");
        }
        Console.ReadKey();            
    }

    static void VarChangedEventHanler(object sender,PropertyChangedEventArgs e)
    {
        Console.WriteLine("{0} has changed",sender.ToString());
    }
}


public class ObservableVar<T> : INotifyPropertyChanged
{
    private T value;

    public ObservableVar(T _value)
    {
        this.value = _value;
    }

    public T Value
    {
        get { return value; }
        set
        {
            if (!this.value.Equals(value)) //null check omitted
            {
                this.value = value;
                if (PropertyChanged != null)
                {
                    PropertyChanged(this, new PropertyChangedEventArgs("Value"));
                }
            }
        }
    }
    public event PropertyChangedEventHandler PropertyChanged;


    public static implicit operator T(ObservableVar<T> observable)
    {
        return observable.Value;
    }
}

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM