.net 具有多个构造函数的记录类型

qjp7pelc  于 2022-12-24  发布在  .NET
关注(0)|答案(5)|浏览(113)

如何在C#中为一个记录类型创建多个构造函数
我创建了如下的记录类型:

public record Person(int Id, string FirstName, string LastName)

现在我想引入另一个没有参数的构造函数重载,我该怎么做呢?在一个普通类中,我会这样做:

public class Person
{
    public int Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }

    public Person()
    {
        
    }

    public Person(int id, string firstName, string lastName)
    {
        Id = id;
        FirstName = firstName;
        LastName = lastName;
    }
}
fkvaft9z

fkvaft9z1#

只需像这样添加所需的构造函数:

record Rank(int level, string description);

record Manager(string FirstName, Rank rank) {
  public Manager() : this("", new(0, "Entry")) { }

  // public Manager(string FirstName, Rank rank) auto generated by compiler
}
xmd2e60i

xmd2e60i2#

您可以编写如下代码:

public record Person
{
    public int Id { get; init; }
    public string FirstName { get; init; }
    public string LastName { get; init; }
    //constructor
    public Person()
    {
        //init or do something
    }
    //overload constructor
    public Person(int id, string firstName, string lastName)
    {
        Id = id;
        FirstName = firstName;
        LastName = lastName;
    }
}
klh5stk1

klh5stk13#

使用可选参数。

public record Person(int Id = default, string FirstName = null, string LastName = null);
p8h8hvxi

p8h8hvxi4#

你可以这样写

public record Person(int Id,string FirstName,string LastName){
   public Person(YourDto item):this(item.Id,item.FirstName,item.LastName){} 
}

因此,在构造函数中可以传递Dto项。

gcuhipw9

gcuhipw95#

当你有一个基本记录时,你也可以这样扩展:

public record Person
{
    public Person(Guid? id = null) { }
}

public record Teacher : Person
{
    public Teacher(Guid id) : base(id) { }
    public Teacher(string firstName, string lastName) : base() { }
}

相关问题