[英]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.