11

カスタム クラスで、プロパティの 1 つを必須にしたいという要件があります。

次のプロパティを必須にするにはどうすればよいですか?

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

4 に答える 4

28

「ユーザーが値を指定する必要がある」という意味の場合は、コンストラクターを介して強制します。

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;
    }
}
于 2012-05-29T06:53:17.727 に答える
2

クライアントコードによって常に値が与えられるようにしたい場合は、コンストラクターのパラメーターとしてそれを要求するのが最善の策です。

class SomeClass
{
    private string _documentType;

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

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

必要に応じて、プロパティのsetアクセサー本体またはコンストラクターで検証を行うことができます。

于 2012-05-29T06:53:40.290 に答える
0

私は別の解決策を使用しましたが、私は最初にオブジェクトを宣言し、特定の状況に基づいて異なる値を持っているため、うまくいきました。ダミーデータを使用する必要があったため、コンストラクターを使用したくありませんでした。

私の解決策は、クラスでプライベート セットを作成することでした (public get)。オブジェクトの値はメソッドによってのみ設定できます。例えば:

public void SetObject(string mandatory, string mandatory2, string optional = "", string optional2 = "") 
于 2016-11-09T08:51:31.040 に答える