Tracking changed (unsaved) objects

I have a class that is serialized to and from an XML file when the user decided to open or save. I try to add typical functionality when, when I try to close a form with saved changes, the form warns them and gives them the option to save until they close.

I added the HasUnsavedChanges property to my class, which my form validates before closing. However, it is a little annoying that my properties have changed from something like this.

 public string Name { get; set; } 

to that...

 private string _Name; public string Name { get { return _Name; } set { this._Name = value; this.HasUnsavedChanges = true; } } 

Is there a better way to track class instance changes? For example, is there some standard way that I can “hash” an instance of a class into a value that I can use to compare the latest version with the saved version without omitting every property in the class?

+4
source share
1 answer

You can reduce parts of the properties to separate lines:

 private int _foo; public int Foo { get { return _foo; } set { SetProperty(ref _foo, value); } } 

Add this to your base class:

 private bool _modified; protected void SetProperty<TValue>( ref TValue member, TValue newValue, IEqualityComparer<TValue> equalityComparer) { var changed = !equalityComparer.Equals(member, newValue); if(changed) { member = newValue; _modified = true; } } protected void SetProperty<TValue>(ref TValue member, TValue newValue) { SetProperty(ref member, newValue, EqualityComparer<TValue>.Default); } 
+6
source

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


All Articles