2016-08-29 62 views
1

我想驗證一個null屬性,並且想返回一個空字符串(如果它爲NULL)。對於我創建了一個類象下面這樣:返回之前驗證null屬性

public class TestValue 
{ 
    public string CcAlias 
    { 
     get 
     { 
      return string.IsNullOrEmpty(CcAlias) ? string.Empty : CcAlias; 
     } 
     set 
     { 
      CcAlias = CcAlias ?? string.Empty; 
     } 
    } 
} 

並測試了我的類下面的代碼:

System.StackOverflowException was unhandled 
    HResult=-2147023895 
    Message=Exception of type 'System.StackOverflowException' was thrown. 
    InnerException: 
+0

如果您正在執行任何自定義代碼,則不能使用自動屬性。在自定義功能的情況下(就像你正在做的那樣),你必須自己實現屬性的代碼(包括存儲和檢索來自成員變量的值)。 –

回答

3

您的二傳手:

private void TestMethod() 
    { 
     var testValue = new TestValue(); 
     testValue.CcAlias = null; 

     MessageBox.Show(testValue.CcAlias); 
     //I thought an empty string will be shown in the message box. 
    } 

不幸的錯誤來了其在下面說明和吸氣者遞歸地調用自己:

set 
{ 
    CcAlias = CcAlias ?? string.Empty; 
} 

這稱爲CcAlias吸氣劑,它又將本身再次調用(通過測試​​)並一次又一次地導致StackOverflowException

您需要聲明支持字段,並將其設置在二傳手:

public class TestValue 
{ 
    private string __ccAlias = string.Empty; // backing field 

    public string CcAlias 
    { 
     get 
     { 
      // return value of backing field 
      return string.IsNullOrEmpty(_ccAlias) ? string.Empty : _ccAlias; 
     } 
     set 
     { 
      // set backing field to value or string.Empty if value is null 
      _ccAlias = value ?? string.Empty; 
     } 
    } 
} 

所以你的字符串存儲在支持字段_ccAlias和你的getter返回此字段的值。
您的設置者現在設置此字段。關於setter的參數在關鍵字value中傳遞。

+0

這很有道理!非常感謝讓我理解這個問題。 –