2017-08-09 24 views
1

我想在c#中創建一個結構,其中您有配對值,如果設置了一個值,則另一個值將自動設置爲相反。舉例來說,如果我有喜歡的配對:c#中有「零和」變量嗎?

{ 
    public bool Courageous; 
    public bool Cowardly; 
} 

因此,如果這兩個中的一個被設定,其他獲得「未設置」。是否存在相關的零和變量?

+3

您可以爲這些屬性定義您自己的setters和getters。 –

回答

2

您可以嘗試性

{ 
    private bool _courageous; 
    public bool Courageous 
    { 
     get 
     { 
      return _courageous; 
     } 
     set 
     { 
      _courageous = value; 
      _cowardly = !value; 
     } 
    } 

    private bool _cowardly; 
    public bool Cowardly 
    { 
     get 
     { 
      return _cowardly; 
     } 
     set 
     { 
      _cowardly = value; 
      _courageous = !value; 
     } 
    } 
} 

或者爲zzzzbovAmy表明,一個支持字段

{ 
    private bool _courageous; 
    public bool Courageous 
    { 
     get 
     { 
      return _courageous; 
     } 
     set 
     { 
      _courageous = value; 
     } 
    } 

    public bool Cowardly 
    { 
     get 
     { 
      return !_courageous; 
     } 
     set 
     { 
      _courageous = !value; 
     } 
    } 
} 

中或不支持字段,see other answer

{ 
    public bool Courageous{ get; set; } 
    public bool Cowardly { get { return !Courageous; } set { Courageous = !value; } } 
} 
+3

他們可以共享相同的後臺字段。不需要兩個字段。 – Amy

+0

你們很棒。我喜歡。我認爲在C#中構建一個比通過屬性更容易聲明的構造是一個超級想法。不過,我喜歡它! -su –

+1

@Amy沒錯,他們可以分享相同的支持領域。但是,爲每個屬性保留單獨的字段是一個很好的設計實踐,這可能有助於未來。 –

5

不要暴露直接的屬性,而不是使用屬性訪問到所需變異私有字段:

{ 
    private bool _courageous; 
    private bool _cowardly; 

    public bool Courageous 
    { 
     get { return _courageous; } 
     set 
     { 
      _courageous = value; 
      _cowardly = !value; 
     } 
    } 

    public bool Cowardly 
    { 
     get { return _cowardly; } 
     set 
     { 
      _cowardly = value; 
      _courageous = !value; 
     } 
    } 
} 

或者更簡單地說在這種情況下,因爲你只有兩個bool S的總是對方的邏輯反:

{ 
    public bool Courageous{ get; set; } 
    public bool Cowardly { get { return !Courageous; } set { Courageous = !value; } } 
} 

您的具體情況將確定您是否可以使用公共支持字段並在一個(或其他)屬性公開公開的屬性中執行突變,或者將需要具有單獨的支持字段和更復雜的訪問器。

但是一般的觀點是,屬性和屬性訪問器可以用來製作幾乎任何你需要的行爲。

+3

在你的第二個例子中使'courageous'成爲一個屬性。這就是'公共布爾勇敢{get;設置;}' –

+0

@JIm - 好,趕上,謝謝。 – Deltics