简体   繁体   English

C# 9.0 记录具有非空属性但具有默认值的构造函数

[英]C# 9.0 Record constructor with non-nullable property but with default values

I am trying to define a record type for the following, instead of being a class我正在尝试为以下内容定义记录类型,而不是 class

public class Contact
{
    public string Name {get;set;}
    public string Email {get;set;}
    public string PhoneNo  {get;set;}
    public DateTime UpdatedAt {get;set;} = DateTime.Now;
}

Since UpdatedAt is a non-nullable field, if I am using the most basic constructor of a record, we will need to pass DateTime.Now everytime we call the record.由于UpdatedAt是一个不可为 null 的字段,如果我使用记录的最基本构造函数,我们将需要传递DateTime.Now每次我们调用记录。 Is there any other way to do it?还有其他方法吗? Instead of doing this:而不是这样做:

public record Contact(string Name, string Email,string PhoneNo, DateTime UpdatedAt);

var records = new Contact("My Name", "a@abc.com", "123456", DateTime.Now)

You can give a record type a constructor, so add one that takes all 4 properties, but make the DateTime nullable and default to null .您可以为record类型提供一个构造函数,因此添加一个接受所有 4 个属性的构造函数,但使DateTime可为空并默认为null If it's null then have the constructor use DateTime.Now .如果它是 null 则让构造函数使用DateTime.Now For example:例如:

public record Contact
{
    public Contact(string name, string email, string phoneNo, DateTime? updatedAt = null)
    {
        this.Name = name;
        this.Email = email;
        this.PhoneNo = phoneNo;
        this.UpdatedAt = (updatedAt ?? DateTime.Now);
    }

    public string Name {get;set;}
    public string Email {get;set;}
    public string PhoneNo  {get;set;}
    public DateTime UpdatedAt {get;set;};
}

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

相关问题 C# 9.0 记录 - 不可为空的引用类型和构造函数 - C# 9.0 records - non-nullable reference types and constructor C# 中的不可为空的只读引用和空的私有默认构造函数导致警告 CS8618 - Non-nullable readonly references and empty private default constructor in C# result in warning CS8618 C#8中Non-Nullable引用类型的默认值是多少? - What is the default value of Non-Nullable reference types in C# 8? C#10 可空模式:如何告诉编译器我在构造函数中间接设置了不可为空的属性? - C#10 nullable pattern: how to tell the compiler I set the non-nullable property in the constructor indirectly? 在 C# 中创建不可为 Null 的类型 - Create Non-Nullable Types in C# C# 非空字段:Lateinit? - C# non-nullable field: Lateinit? 不可为空的引用类型的默认值 VS 不可为空的值类型的默认值 - Non-nullable reference types' default values VS non-nullable value types' default values 在 C# 中是否可以为可空值和不可空值编写隐式转换运算符? - Is it possible in C# to write an implicit conversion operator for both nullable and non-nullable values? 构造函数是在 C# 中的类中初始化不可为空属性的唯一方法吗? - Is constructor the only way to initialize non-nullable properties in a class in C#? C#可空与不可空DateTime标签 - C# Nullable vs Non-Nullable DateTime tags
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM