c# marking class property as dirty

前端 未结 11 2374
盖世英雄少女心
盖世英雄少女心 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 20:11

    When you really do want a dirty flag at the class level (or, for that matter, notifications) - you can use tricks like below to minimise the clutter in your properties (here showing both IsDirty and PropertyChanged, just for fun).

    Obviously it is a trivial matter to use the enum approach (the only reason I didn't was to keep the example simple):

    class SomeType : INotifyPropertyChanged {
        private int foo;
        public int Foo {
            get { return foo; }
            set { SetField(ref foo, value, "Foo"); }
        }
    
        private string bar;
        public string Bar {
            get { return bar; }
            set { SetField(ref bar, value, "Bar"); }
        }
    
        public bool IsDirty { get; private set; }
        public event PropertyChangedEventHandler PropertyChanged;
        protected void SetField(ref T field, T value, string propertyName) {
            if (!EqualityComparer.Default.Equals(field, value)) {
                field = value;
                IsDirty = true;
                OnPropertyChanged(propertyName);
            }
        }
        protected virtual void OnPropertyChanged(string propertyName) {
            var handler = PropertyChanged;
            if (handler != null) {
                handler(this, new PropertyChangedEventArgs(propertyName));
            }
        }
    }
    

    You might also choose to push some of that into an abstract base class, but that is a separate discussion

提交回复
热议问题