[英]How to make a property required in 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
但验证:
public YourType(string documentType) {
DocumentType = documentType;
}
private string documentType;
public string DocumentType {
get { return documentType; }
set {
// TODO: validate
documentType = value;
}
}
在 c#11 中,出现了强制进行属性初始化的required
关键字。
public class MyClass
{
public required string Name { get; init; }
}
new MyClass(); // compile error
new MyClass { Name = "Me" }; // works fine
更多在这里
如果你的意思是你希望它总是被客户端代码赋予一个值,那么你最好的办法是在构造函数中要求它作为参数:
class SomeClass
{
private string _documentType;
public string DocumentType
{
get
{
return _documentType;
}
set
{
_documentType = value;
}
}
public SomeClass(string documentType)
{
DocumentType = documentType;
}
}
您可以在属性的set
访问器主体或构造函数中进行验证(如果需要)。
向属性添加必需的属性
Required(ErrorMessage = "DocumentTypeis required.")]
public string DocumentType
{
get
{
return _documentType;
}
set
{
_documentType = value;
}
}
有关自定义属性详细信息,请单击此处
我使用了另一种解决方案,不完全是您想要的,但对我来说很好,因为我首先声明了对象并根据具体情况我有不同的值。 我不想使用构造函数,因为我不得不使用虚拟数据。
我的解决方案是在类上创建私有集(公共获取),您只能通过方法设置对象上的值。 例如:
public void SetObject(string mandatory, string mandatory2, string optional = "", string optional2 = "")
这一个班轮在 C# 9 中工作:
public record Document(string DocumentType);
new Document(); // compiler error
new Document("csv"); // correct way to construct with required parameter
这解释了它是如何工作的。 在上面的代码中,Document 是类或“记录”的名称。 第一行代码实际上定义了整个类。 除了这个解决方案本质上创建了一个必需的 DocumentType 属性(自动实现的构造函数需要)之外,因为它使用记录,所以还有其他含义。 因此,这可能并不总是合适的解决方案,C# 11 required
关键字有时仍然会派上用场。 仅使用record
类型不会自动使属性成为必需。 上面的代码是一种使用记录的特殊语法方式,它本质上具有这种效果,并且只使属性init
并导致自动实现解构器。
一个更好的例子是使用 int 属性而不是字符串,因为字符串仍然可以是空的。 不幸的是,我不知道有什么好方法可以在记录中进行额外验证以确保字符串不为空或 int 在范围内等。您必须深入了解 TOP(类型驱动开发)兔子洞,这可能不是一件坏事。 您可以创建自己的类型,该类型不允许您接受范围之外的空字符串或整数。 不幸的是,这种方法会导致运行时发现无效输入而不是编译时间。 使用静态分析和元数据可能有更好的方法,但我离开 C# 太久了,对此一无所知。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.