Base class awareness of property changes in derived classes

I was wondering if anyone has a possible solution to the following problem ... I have a base class from which a series of derived classes are inherited. The base class takes care of whether the properties of the derived class have changed. This is done to set "IsDirty" for the data transfer object.

The traditional approach would be to set the IsDirty boolean flag declared in the base class. I was hoping to avoid this somehow and wondered if there could be a different approach? I am concerned that the developer did not forget to set the flag in the equivalent set operation for the property in the derived class. I considered the idea of ​​creating a generic "SetProperty" method that would take the name and value of a property, but I thought there might be something more elegant.

As a remark, ideas regarding the use of reflection are not a problem. Regardless of the cost of thinking, I would like to show a way to do this and continue to work on further improvement.

+3
source share
3 answers

INotifyPropertyChanged? PropertyChanged chill. - ( -, ?).

: http://monotorrent.blogspot.com/2009/12/yet-another-inotifypropertychanged-with_06.html

+3

( ) . isDirty - .

Factory .

, , , (, State), .

+1

(Quick and dirty). What about this one? (Your implementation of GetHashCode may be different - I used ReSharper to automatically create this)

    public abstract class Animal
    {
        private int _originalHash;

        public string Name { get; set; }
        public int Age { get; set; }

        public Animal(string name, int age)
        {
            this.Name = name;
            this.Age = age;

            this._originalHash = GetHashCode();
        }


        public override sealed int GetHashCode()
        {
            unchecked
            {
                return ((Name != null ? Name.GetHashCode() : 0) * 397) ^ Age;
            }
        }

        public bool IsDirty
        {
            get
            {
                return this._originalHash != GetHashCode();
            }
        }
    }

    public class Cat : Animal
    {
        public Cat(string name, int age)
            : base(name, age)
        {
        }
    }

Used for testing ...

var cat = new Cat("BobTheCat", 12);
Console.WriteLine(cat.IsDirty);
cat.Age = 13;
Console.WriteLine(cat.IsDirty);

Results:

False true

0
source

Source: https://habr.com/ru/post/1726297/


All Articles