开发者

Set all properties of same name recursively

I have an IsDirty property of type bool 开发者_如何学编程on most of my objects.

My base object is called Client, but contains several inner collections e.g.: Client.Portfolios.Policies.Covers.CoverOptions, each object type has an IsDirty property:

  • Client.IsDirty
  • Client.Portfolios.IsDirty
  • Client.Portfolios.Policies.IsDirty
  • etc...

How do I recursively set all IsDirty properties?


If you want it truly recursive, I recommend to create an interface that is designed around this idea. For example:

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);
}

And then in each of your objects, you would implement these something like this:

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);
    }
}


Unless they all share a common base class or interface which defines the IsDirty property, you'll need to use reflection or dynamic (C# 4.0 only). The latter is much easier to use, and can be reduced to.

foreach (var obj in myobjects) {
    dynamic dynobj = obj;
    dynobj.IsDirty = false;
}

Still, if you have the ability to modify your objects, you could create and add the interface to each one. It's better than dynamic, mainly for performance and compile time checking

interface IDirtyObject {
    bool IsDirty { get; set; }
}

class ExampleDirtyObject : IDirtyObject {
    public bool IsDirty { get; set; }
}

foreach (IDirtyObject obj in myobjects)
    obj.IsDirty = false;
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜