如何在C#中需要的属性? [英] How to make a property required in c#?

查看:106
本文介绍了如何在C#中需要的属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我要让需要我的属性中的一个自定义类的要求。



我怎样才能使所需的下列财产?



 公共字符串DocumentType 
{
得到
{
返回_documentType;
}

{
_documentType =价值;
}
}


解决方案

如果你的意思是用户必须指定一个值,然后通过构造迫使它:

 公共YourType(字符串documentType){
documentType = documentType; // TODO验证;它可以为空?空白?
}
公共字符串DocumentType {获取;私人集;}

现在你而不指定文件类型不能创建一个实例,并且它不能在该时间之后被删除。你也可以让设置,但验证:

 公共YourType(串documentType){
documentType = documentType;
}
私人字符串documentType;
公共字符串DocumentType {
{返回documentType; }
集合{
// TODO:验证
documentType =价值;
}
}


I have requirement in a custom class where I want to make one of my properties required.

How can I make the following property required?

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

解决方案

If you mean "the user must specify a value", then force it via the constructor:

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

Now you can't create an instance without specifying the document type, and it can't be removed after that time. You could also allow the set but validate:

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

这篇关于如何在C#中需要的属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆