record
实例时,如果你想使用with
关键字,你可以忽略一些字段,而不是将它们复制到新实例中。
在下面的示例中,我有一个Hash
属性。由于计算成本非常高,所以只有在需要时才会计算并缓存(我有一个深度不可变的记录,所以对于一个实例,哈希值永远不会改变)。public record MyRecord {
// All truely immutable properties
public int ThisAndManyMoreComplicatedProperties { get; init; }
// ...
// Compute only when required, but then cache it
public string Hash {
get {
if (hash == null)
hash = ComputeHash();
return hash;
}
}
private string? hash = null;
}
当调用时
MyRecord myRecord = ...;
var changedRecord = myRecord with { AnyProp = ... };
changedRecord
包含了来自 myRecord
的 hash
值,但是我想要的是默认的 null
值。
有没有可能将 hash
字段标记为“短暂”/“内部”/“真正私有”...,或者我需要编写自己的复制构造函数来模仿这个特性?
with
克隆记录时,新记录将获得现有哈希值(它是一个克隆,所以应该具有相同的哈希值),而不是通过再次运行哈希来计算,而只是通过复制该值(因此很便宜)。但是,您的 AnyProp setter(因为它正在更改记录,因此也更改了哈希)肯定会再次将哈希设置为 null,因此下次请求时将重新计算它(考虑 AnyProp 的新值),并且复制构造函数将使用 AnyProp setter 为 AnyProp 提供新值,从而使哈希值变为 null。 - Caius Jard