.net 更改嵌套记录中的属性值

6yjfywim  于 2023-11-20  发布在  .NET
关注(0)|答案(2)|浏览(143)

是否可以使用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")的值。我如何才能最有效地做到这一点?

vh0rcniy

vh0rcniy1#

您可以嵌套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);
}

字符串

ybzsozfc

ybzsozfc2#

你可以使用LeviySoft.Visor来避免嵌套with的尴尬:

[Optics(withNested: true)]
internal partial record Company(string Name, Branch Branch);
[Optics(withNested: true)]
internal partial record Branch(string Location, IEnumerable<Employee> Employees);
[Optics]
internal partial record Employee(string FirstName);

var original = new Company(...)

var updated = Company.FocusBranch.LocationLens.Set("Warshaw")(original)

字符串
至于IELTS-你可以为IENumerables实现自己的IProperty,以this为例。请注意,使用非不可变的集合接口会破坏记录的值比较(这就是我没有为IELTS实现IProperty的原因)

相关问题