【问题标题】:setting a default value for an ICollection<string> DTO's property in c# [closed]在 C# 中为 ICollection<string> DTO 的属性设置默认值 [关闭]
【发布时间】:2021-06-07 02:27:11
【问题描述】:

如果我有一个 ICollection 属性并且我需要设置一个默认字符串值。

public class UserDTO : LoginUserDTO
{
    public string FirstName { get; set; }
    public string LastName { get; set; }

    [DataType(DataType.EmailAddress)]
    public string Email { get; set; }
    public ICollection<string> Roles { get; set; } = new List<string>() { "User" };
} 

每次在控制器中使用此 DTO 时,我都需要默认角色为用户,但是,正如您在下面的招摇图片中看到的那样,它始终为空

如何将默认角色设置为用户??

【问题讨论】:

    标签: c# properties default-value icollection


    【解决方案1】:

    这是正确的语法。

    public ICollection<string> Roles { get; set; } = new List<string>() { "User" };
    

    您的示例无法运行,因为您尝试在未实例化的集合中添加值。 (当时“角色”为空)。

    第二期。由于“Add”返回“void”,所以不能赋值给集合本身。

    此示例仅适用于 C# 6 或更高版本。如果您不使用它,则必须在构造函数中使用“旧方式”:

    public UserDTO() 
    {
        Roles = new List<string>() { "User" };
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2010-10-16
      • 2012-04-07
      • 1970-01-01
      • 1970-01-01
      • 2011-03-21
      • 2014-08-16
      • 1970-01-01
      相关资源
      最近更新 更多