我的大多数对象都具有IsDirty类型的bool属性。

我的基础对象称为Client,但包含多个内部集合,例如:Client.Portfolios.Policies.Covers.CoverOptions,每种对象类型都有一个IsDirty属性:


Client.IsDirty
Client.Portfolios.IsDirty
Client.Portfolios.Policies.IsDirty
等等...


如何递归设置所有IsDirty属性?

最佳答案

如果您希望它真正递归,我建议创建一个围绕该想法设计的接口。例如:

public interface IDirtyObject
{
    /// <summary>Gets a value indicating whether this object is dirty.</summary>
    bool IsDirty { get; set; }   // or perhaps get only?

    /// <summary>Sets this object, as well as dirty objects within it, to
    /// the specified dirty value.</summary>
    void SetAllDirty(bool dirty);
}


然后在每个对象中,您将实现以下类似内容:

public class MyDirtyObject : IDirtyObject
{
    // (note you can have get and set here even if the interface has only get)
    public bool IsDirty { get; set; }

    public IDirtyObject MyOtherDirtyObject;
    public List<IDirtyObject> MoreDirtyObjects;

    public void SetAllDirty(bool dirty)
    {
        IsDirty = dirty;

        if (MyOtherDirtyObject != null)
            MyOtherDirtyObject.SetAllDirty(dirty);

        if (MoreDirtyObjects != null)
            foreach (var obj in MoreDirtyObjects)
                obj.SetAllDirty(dirty);
    }
}

10-06 11:09