更改嵌套记录中的 属性 值

Changing property value in nested records

是否可以使用 with 关键字为嵌套 属性 创建具有不同值的嵌套记录的新实例 - 两种情况:简单 属性 和集合?让我们看一个例子:

class Program
{
    static void Main(string[] args)
    {
        var company = new Company(
            Name: "Company1",
            Branch: new Branch(
                Location: "Krakow",
                Employees: new[]
                {
                    new Employee("Robert")
                }));

        Console.WriteLine(company);
    }
}

internal record Company(string Name, Branch Branch);
internal record Branch(string Location, IEnumerable<Employee> Employees);
internal record Employee(string FirstName);

在上面的示例中,我想创建一个新记录,但更改了分支位置 ("Krakow") 和员工姓名 ("Robert") 的值。我怎样才能最有效地做到这一点?

您可以嵌套 with 表达式:

var clone = company with {
    Name = "Company2",
    Branch = company.Branch with {
        Location = "Warshaw",
        Employees = new[]
        {
            company.Branch.Employees.First() with 
            {
                FirstName = "Bob"
            }
        }}};

Console.WriteLine(clone);
foreach (var e in clone.Branch.Employees)
{
    Console.WriteLine(e);
}