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

Sha*_*ngh 9 c#

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

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

public string DocumentType
{
    get
    {
        return _documentType;
    }
    set
    {
        _documentType = value;
    }
}
Run Code Online (Sandbox Code Playgroud)

Her*_*rvé 23

.NET 7 或更高版本

句法

public class MyClass
{
    public required string Name { get; init; }
}

new MyClass(); // illegal
new MyClass { Name = "Me" }; // works fine
Run Code Online (Sandbox Code Playgroud)

评论

属性必须required声明一个setter (或者)。initset

属性或设置器上的访问修饰符不能比它们的包含类型更不可见,因为在某些情况下它们会导致无法初始化类。

public class MyClass
{
    internal required string Name { get; set; } // illegal
}
Run Code Online (Sandbox Code Playgroud)

文档

.NET 6 或更早版本

这个答案


Mar*_*ell 21

如果您的意思是"用户必须指定一个值",那么通过构造函数强制它:

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

现在,您无法在未指定文档类型的情况下创建实例,并且在此之后无法将其删除.您也可以允许set但验证:

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