2012-05-29 22 views
7

我有一個自定義類中的需求,我想讓我的一個屬性需要。如何在c#中創建一個屬性?

我如何製作以下屬性?

public string DocumentType 
{ 
    get 
    { 
     return _documentType; 
    } 
    set 
    { 
     _documentType = value; 
    } 
} 
+0

你是什麼意思的「做一個屬性所需」? –

+0

「使所需物業」意味着物業需要價值,它不能留空。 –

回答

17

如果你的意思是「用戶必須指定的值」,然後通過構造迫使它:

public YourType(string documentType) { 
    DocumentType = documentType; // TODO validation; can it be null? blank? 
} 
public string DocumentType {get;private set;} 

現在你不能沒有指定文件類型創建一個實例,它可以那段時間之後不會被刪除。你也可以讓set但驗證:

public YourType(string documentType) { 
    DocumentType = documentType; 
} 
private string documentType; 
public string DocumentType { 
    get { return documentType; } 
    set { 
     // TODO: validate 
     documentType = value; 
    } 
} 
2

如果你的意思是你想它總是已經由客戶端代碼中給出的數值,那麼最好的辦法是,要求其作爲構造函數的參數:

class SomeClass 
{ 
    private string _documentType; 

    public string DocumentType 
    { 
     get 
     { 
      return _documentType; 
     } 
     set 
     { 
      _documentType = value; 
     } 
    } 

    public SomeClass(string documentType) 
    { 
     DocumentType = documentType; 
    } 
} 

你可以做你的驗證 - 如果你需要 - 無論是在酒店的set訪問身體或在構造函數中。

1

添加必需的屬性,歡迎使用屬性

Required(ErrorMessage = "DocumentTypeis required.")] 
public string DocumentType 
     { 
      get 
      { 
       return _documentType; 
      } 
      set 
      { 
       _documentType = value; 
      } 
     } 

對於自定義屬性的詳細Click Here

+5

RequiredAttribute沒有語言支持;一些UI框架可能會爲這樣的屬性增加一些特殊的含義,但這完全取決於圖書館 –

0

我使用其他的解決辦法,而不是你想要什麼,但對我來說工作得很好,因爲我第一次和基於聲明的對象在具體情況下我有不同的價值觀。我不想使用構造函數,因爲我不得不使用虛擬數據。

我的解決方案是在類(public get)上創建私有集合,您只能通過方法設置對象的值。例如:

public void SetObject(string mandatory, string mandatory2, string optional = "", string optional2 = "") 
相關問題