Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
232 views
in Technique[技术] by (71.8m points)

c# - How to check if an object has changed?

I have an object, which contains other objects, which contain other objects, including lists, etcetera. This object is databound to a form, exposing numerous fields to the user in different tabs. I also use master-child datagridviews.

Any idea how to check if anything has changed in this object with respect to an earlier moment? Without (manually) adding a changed variable, which is set to true in all (>100) set methods.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

As Sll stated, an dirty interface is definitely a good way to go. Taking it further, we want collections to be dirty, but we don't want to necessarily set ALL child objects as dirty. What we can do, however is combine the results of their dirty state, with our own dirty state. Because we're using interfaces, we're leaving it up to the objects to determine whether they are dirty or not.

My solution won't tell you what is dirty, just that the state of any object at any time is dirty or not.

public interface IDirty
{
    bool IsDirty { get; }
}   // eo interface IDirty


public class SomeObject : IDirty
{
    private string name_;
    private bool dirty_;

    public string Name
    {
        get { return name_; }
        set { name_ = value; dirty_ = true; }
    }
    public bool IsDirty { get { return dirty_; } }
}   // eo class SomeObject


public class SomeObjectWithChildren : IDirty
{
    private int averageGrades_;
    private bool dirty_;
    private List<IDirty> children_ = new List<IDirty>();

    public bool IsDirty
    {
        get
        {
            bool ret = dirty_;
            foreach (IDirty child in children_)
                dirty_ |= child.IsDirty;
            return ret;
        }
    }

}   // eo class SomeObjectWithChildren

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...