如何制作c#所需的属性?

我有一个自定义类的要求,我想要我的一个属性需要。

如何使以下属性成为必需?

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但validation:

 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访问器主体或构造函数中进行validation – 如果需要 – 。

将所需属性添加到propety

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

自定义属性详细信息单击此处

我使用了另一种解决方案,不完全是你想要的,但对我来说很好,因为我首先声明了对象,并根据具体情况我有不同的值。 我不想使用构造函数,因为我不得不使用虚拟数据。

我的解决方案是在类上创建私有集(public get),并且只能通过方法设置对象的值。 例如:

 public void SetObject(string mandatory, string mandatory2, string optional = "", string optional2 = "")