2015-07-01 53 views
0

我有一個類:穿越家長和設置屬性有條件

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

我想將類屬性設置爲函數的結果。當對象被設置時,我會如何去做這件事?

+0

「class property」是什麼意思?屬性屬於類的每個實例(它們是非靜態的)。 – ryanyuyu

+0

你的問題(和代碼..)有點不清楚......你能提供一個數據樣本嗎? (輸入+請求輸出) – Amit

回答

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

,你就可以說是依賴上屬性的值(你應該真正做到不分,公然暴露在他們),並具有:你可以重新calucluate派生值只要有人需要它他們在設置時重新計算派生值,但問題是ParentThat IsInCharge屬性不僅可以在該單元的屬性發生更改時發生更改,而且可以在父項的任何屬性發生更改時改變,並且沒有真正的好方法(給定API提供)知道你父母的任何財產何時發生了變化。當任何屬性改變時,你必須給Unit一個事件觸發,然後當它們中的任何一個觸發重新計算值(甚至當單元祖先可能已經改變時連接/取消附加事件處理程序)。

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; 
} 
+0

而-1是...? – Amit