2014-05-13 40 views

回答

3

沒有內置任何東西,你需要自己寫這個邏輯。有三種方法可以做到這一點,在下降的「好習慣」的順序:

  1. 與枚舉更換兩個:當你有兩個相互排斥的狀態,你最好合併成一個單一的具有多個狀態的值。如果你真的需要作爲單獨的布爾值,你可以編寫只讀屬性來檢查中心狀態。

    public enum MyState 
    { 
        NoState, 
        IsStateA, 
        IsStateB, 
    } 
    public MyState State { get; set; } 
    public bool IsStateA { get { return State == MyState.IsStateA; } } 
    public bool IsStateB { get { return State == MyState.IsStateB; } } 
    
  2. 強制它在業務邏輯層:在這種情況下,您只需執行在UI的限制,或任何輸入的來源。無論何時嘗試切換,都要檢查其他狀態並適當地通知/更改。

  3. 寫setter邏輯切換另一個:當設置一個,設置另一個。

    private bool _StateA; 
    private bool _StateB; 
    public bool IsStateA { 
        get { return _StateA; } 
        set { 
        _StateA = value; 
        if (value) _StateB = false; // If this is now true, falsify the other. 
        } 
    } 
    public bool IsStateB { 
        get { return _StateB; } 
        set { 
        _StateB = value; 
        if (value) _StateA = false; // If this is now true, falsify the other. 
        } 
    } 
    

選擇#1是真的來處理這樣的「三個態」情況下的最佳方式,但其他人也可以工作。

+0

1我認爲1.爲這種情況下的最佳解決方案。將枚舉重命名爲A和B以匹配作者的上下文c:p – Kilazur

+0

@Kilazur - #1遠遠超出最佳值(但對於重命名它們是正確的) – Bobson

1

爲什麼不使用簡單的獲取/設置邏輯?

private bool a; 

public bool A 
{ 
    get { return a; } 
    set 
    { 
     if (value == B) 
     { 
      throw new Exception("A and B have the same boolean value!"); 
     } 
     else 
      a = value; 
    } 
} 

或允許A和B,以在任一狀態進行設置,但無論具有用於存儲邏輯有效性的第三布爾:

public bool IsValid { get { return (A == B); } } 
相關問題