c# marking class property as dirty

前端 未结 11 2339
盖世英雄少女心
盖世英雄少女心 2020-11-29 19:32

The following is a simple example of an enum which defines the state of an object and a class which shows the implementation of this enum.

public enum Status         


        
11条回答
  •  一整个雨季
    2020-11-29 19:59

    You could also think about boxing your variables, which comes at a performance cost, but also has its merits. It is pretty consise and you cannot accidentally change a value without setting your dirty status.

    public class Variable
    {
        private T _value;
        private readonly Action _onValueChangedCallback;
    
        public Variable(Action onValueChangedCallback, T value = default)
        {
            _value = value;
            _onValueChangedCallback = onValueChangedCallback;
        }
    
        public void SetValue(T value)
        {
            if (!EqualityComparer.Default.Equals(_value, value))
            {
                _value = value;
                _onValueChangedCallback?.Invoke(value);
            }
        }
    
        public T GetValue()
        {
            return _value;
        }
    
        public static implicit operator T(Variable variable)
        {
            return variable.GetValue();
        }
    }
    

    and then hook in a callback that marks your class as dirty.

    public class Example_Class
    {
        private StatusEnum _Status = StatusEnum.New;
    
        private Variable _ID;
        private Variable _Name;
    
        public StatusEnum Status
        {
            get { return _Status; }
            set { _Status = value; }
        }
    
        public long ID => _ID;
        public string Name => _Name;
    
        public Example_Class()
        {
             _ID = new Variable(l => Status = StatusEnum.Dirty);
             _Name = new Variable(s => Status = StatusEnum.Dirty);
        }
    }
    

提交回复
热议问题