开发者

Tracking changed (unsaved) objects

I have a class which is serialized to and from an XML file when the user decided to open or save. I'm trying to add the typical functionality where when they try to close the form with un-saved changes the form warns them and gives them the option of saving before closing.

I've added a HasUnsavedChanges property to my class, which my form checks before closing. However, it's a little annoying that my properties have changed from something like this ..

public string Name
{
    get;
   set;
}

to this...

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

Is there a better way to track changes to an instance of a class? For example is there some standard way I can "hash" an instance of a class into a value that I can use to compare the most recent vers开发者_如何学编程ion with the saved version without mucking up every property in the class?


You can reduce the property parts to single 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);
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜