穿越父母并有条件地设置财产

时间:2015-07-01 19:12:16

标签: c#

我有一个班级:

class Unit
{
    string Name;
    Unit Parent;       
    bool IsInCharge;
    Unit ParentUnitThatIsInCharge;
}

我想遍历父母找到负责的父母并将其设置为ParentUnitThatIsInCharge。

我有获取ParentUnitThatIsInCharge的函数:

public Unit GetParentUnitThatIsInCharge(Unit unit)
{
    Unit inChargeUnit= null;

    if (unit.Parent != null)
    {
        do
        {
            inChargeUnit= unit.Parent;
        } while (!inChargeUnit.IsInCharge);
    }
    return inChargeUnit;
}

我想将class属性设置为函数的结果。设置对象后我该怎么做呢?

2 个答案:

答案 0 :(得分:1)

ParentUnitThatIsInCharge是派生值。它取决于对象中设置的其他值。只要有人要求,您就可以重新计算该派生值:

    public class Unit
    {
        public string Name { get; set; }
        public Unit Parent { get; set; }
        public bool IsInCharge { get; set; }
        public Unit ParentUnitThatIsInCharge
        {
            get
            {
                return GetParentUnitThatIsInCharge(this);
            }
        }

        public static Unit GetParentUnitThatIsInCharge(Unit unit)
        {
            Unit current = unit;
            while (!current.IsInCharge && current.Parent != null)
            {
                current = current.Parent;
            }
            return current;
        }
    }

或者,你可以使它所依赖的值成为属性(无论你在公开时公开它们应该做什么),并让它们在设置时重新计算派生值,但问题是ParentThat IsInCharge属性不仅可以更改此单元的属性更改,还可以更改任何父级属性的更改,并且没有真正好的方法(在提供API的情况下)知道父级的任何属性何时发生更改。你必须给Unit一个事件,当任何属性改变时触发,然后当它们中的任何一个触发重新计算值时(甚至连接/取消附加事件处理程序,因为单位祖先可能已经改变)

答案 1 :(得分:0)

如果您只想设置给定实例的属性,则根本不需要返回值(尽管您当然可以......)。
只需:

public Unit GetParentUnitThatIsInCharge(Unit unit)
{
    Unit inChargeUnit= null;

    if (unit.Parent != null)
    {
        do
        {
            inChargeUnit= unit.Parent;
        } while (!inChargeUnit.IsInCharge);
    }

    unit.ParentUnitThatIsInCharge = inChargeUnit;
    return inChargeUnit;
}