简体   繁体   English

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

[英]Record type with multiple constructors

How do I create multiple constructors for a record type in C#?如何为 C# 中的记录类型创建多个构造函数?

I created a record type like this:我创建了一个这样的记录类型:

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

Now I want to introduce another constructor overload with no parameters, how can I do that?现在我想引入另一个没有参数的构造函数重载,我该怎么做? In a normal class I would do something like this:在普通的 class 中,我会这样做:

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;
    }
}

The selected answer works for this simple case where all the members are simple types.所选答案适用于所有成员都是简单类型的这种简单情况。 With reference types you usually want to call their constructors etc.对于引用类型,您通常希望调用它们的构造函数等。

The right solution is to simply add the constructor you want like this:正确的解决方案是像这样简单地添加你想要的构造函数:

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
}
                          

Use optional arguments.使用可选的 arguments。

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

You can write your code like below:您可以编写如下代码:

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;
    }
}

you can write it like this:你可以这样写:

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

so, in the constructor you can pass your Dto item.因此,在构造函数中,您可以传递您的 Dto 项。

You can also extend like so when you have a base record:当您有基本记录时,您也可以像这样扩展:

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() { }
}

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

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