カスタム クラスで、プロパティの 1 つを必須にしたいという要件があります。
次のプロパティを必須にするにはどうすればよいですか?
public string DocumentType
{
get
{
return _documentType;
}
set
{
_documentType = value;
}
}
カスタム クラスで、プロパティの 1 つを必須にしたいという要件があります。
次のプロパティを必須にするにはどうすればよいですか?
public string DocumentType
{
get
{
return _documentType;
}
set
{
_documentType = value;
}
}
「ユーザーが値を指定する必要がある」という意味の場合は、コンストラクターを介して強制します。
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;
}
}
クライアントコードによって常に値が与えられるようにしたい場合は、コンストラクターのパラメーターとしてそれを要求するのが最善の策です。
class SomeClass
{
private string _documentType;
public string DocumentType
{
get
{
return _documentType;
}
set
{
_documentType = value;
}
}
public SomeClass(string documentType)
{
DocumentType = documentType;
}
}
必要に応じて、プロパティのset
アクセサー本体またはコンストラクターで検証を行うことができます。
私は別の解決策を使用しましたが、私は最初にオブジェクトを宣言し、特定の状況に基づいて異なる値を持っているため、うまくいきました。ダミーデータを使用する必要があったため、コンストラクターを使用したくありませんでした。
私の解決策は、クラスでプライベート セットを作成することでした (public get)。オブジェクトの値はメソッドによってのみ設定できます。例えば:
public void SetObject(string mandatory, string mandatory2, string optional = "", string optional2 = "")