递归设置同名的所有属性

时间:2010-09-14 05:23:50

标签: c#

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

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

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

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

2 个答案:

答案 0 :(得分:4)

如果你想要它真正的递归,我建议创建一个围绕这个想法设计的界面。例如:

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

答案 1 :(得分:2)

除非它们共享一个定义IsDirty属性的公共基类或接口,否则您需要使用反射或dynamic(仅限C#4.0)。后者更容易使用,可以减少到。

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

但是,如果您能够修改对象,则可以创建并添加每个对象的界面。它比动态更好,主要用于性能和编译时检查

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

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

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