简体   繁体   English

初始化 object 时强制进行属性初始化

[英]Force a property initialization when initializing an object

using System.ComponentModel.DataAnnotations;

public class User
{
    [Required]
    public string FirstName { get; set; }

    [Required]
    public string LastName { get; set; }
}

User user = new User
{
    LastName = "Jane"
};

FirstName and LastName are required, why does the code let me initialize a user without FirstName ? FirstNameLastName是必需的,为什么代码让我初始化没有FirstName的用户? How can I force it so that FirstName must have a value as well?我怎样才能强制它,以便FirstName也必须有一个值?

You can add a constructor that forces you to initialize the property:您可以添加一个强制您初始化属性的构造函数:

public class User
{
    [Required]
    public string FirstName { get; set; }
    public string LastName { get; set; }

    public User(string firstName)
    {
       FirstName = firstName;
    }
}

This will be impossible:这将是不可能的:

User user = new User
{
    LastName = "Jane"
};

You'll have to do it like this:你必须这样做:

User user = new User("something")
{
    LastName = "Jane"
};

Because you can still pass null to your constructor, you also might check this:因为您仍然可以将null传递给您的构造函数,您还可以检查以下内容:

public User(string firstName)
        {
           if(firstName == null)
           {
              throw new ArgumentNullException(nameof(firstName));
           }
           FirstName = firstName;
        }

The [Required] attribute is used for model binding. [Required]属性用于 model 绑定。 If you require the class to have the FirstName property you should add a constructor.如果您需要 class 具有 FirstName 属性,您应该添加一个构造函数。

public class User
{
    [Required]
    public string FirstName { get; set; }
    public string LastName { get; set; }

    public User(string firstName)
    {
        FirstName = firstName;
    }
}

User user = new User("FirstName")
{
    LastName = "Jane"
};

C# 11 introduces this new feature of being able to require a property when initializing an object with the required keyword . C# 11引入了这一新功能,即在使用required关键字初始化 object 时能够要求属性。

You can do something like this:你可以这样做:

public class User
{
    public required string FirstName { get; set; }
    public required string LastName { get; set; }
}

User user = new User
{
    FirstName = "Caffè",
    LastName = "Latte"
};

If you need the constructor, you need to add the [SetsRequiredMembers] attribute to it, like this:如果需要构造函数,则需要为其添加[SetsRequiredMembers]属性,如下所示:

public class User
{
    public required string FirstName { get; set; }
    public required string LastName { get; set; }

    [SetsRequiredMembers]
    public User(string firstName, string lastName) => (FirstName, LastName) = (firstName, lastName);
}

User user = new User("Caffè", "Latte");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM