【问题标题】:Modifying/filtering without mutating object修改/过滤而不改变对象
【发布时间】:2021-09-05 02:20:08
【问题描述】:

好的,假设我有一些 C# 代码可以过滤或重组传入的对象(或对象列表),如下所示:

public Customer GetCustomer()
{
    var customer = _customerAdapter.GetCustomer();
    ModifyCustomer(customer);
    return customer;
}

private void ModifyCustomer(Customer c)
{
   //some changes to customer object
}

这可行,但我更喜欢功能更强大的方法,即保留新客户并返回新客户(修改后的客户)。

深度克隆是要走的路吗?用 C# 编码时是否推荐?

【问题讨论】:

标签: c# functional-programming


【解决方案1】:

最接近的内置功能可能是recordswith 表达式:

public record Person(string FirstName, string LastName)
{
    public string[] PhoneNumbers { get; init; }
}

Person person1 = new("Nancy", "Davolio") { PhoneNumbers = new string[1] };
Person person2 = person1 with { FirstName = "John" };

【讨论】:

  • 酷!还没有(C# 9),但我一定会研究它,并在我自己的项目中使用它!
  • @Cowborg 记录不需要任何运行时更改,因此应该可以通过在 .csproj 中设置 LangVersion 在 .net 框架中使用,即使这不受官方支持。
【解决方案2】:

如果你不能使用 C# 9,那么你可以这样做:

public class Consumer
{
   public readonly string FirstName;
   public readonly string LastName;

   public Consumer(string firstName, string lastName)
   {
       this.FirstName = firstName;
       this.LastName = lastName;
   }

   public Consumer WithFirstName(string firstName)
     => string.Equals(this.FirstName, firstName) 
              ? this 
              : new Consumer(firstName, this.LastName);

   public Consumer WithLastName(string lastName)
     => string.Equals(this.LastName, lastName)
              ? this
              : new Consumer(this.FirstName, lastName);
   }
}

Related dotnet blogpost

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-04-01
    • 1970-01-01
    • 2013-11-23
    • 1970-01-01
    • 1970-01-01
    • 2013-03-12
    • 1970-01-01
    相关资源
    最近更新 更多