我有一条记录,其中包含从构造函数参数之一派生的仅获取属性:
public readonly record struct FooRecord(string Foo)
{
public IList<string> SomeDerivedProperty { get; } = Foo.Split('.').ToList();
}
如果我使用 with
关键字创建记录的副本,则不会在新记录上重新初始化仅获取属性。
FooRecord record1 = new("Hello.World");
FooRecord record2 = record1 with { Foo = "A.B.C" };
Debug.WriteLine(string.Join(".", record2.SomeDerivedProperty)); // Outputs "Hello.World" instead of "A.B.C"
有没有办法让 get-only 属性在被分配新的构造函数参数值后在新记录上重新初始化?
最佳答案
record1 with { Foo = "A.B.C"}
做了两件事 - 复制 record1
,并调用 Foo 的
。根据here,您无法控制记录结构的复制方式。 。这样我们就剩下了init
er Foo
的init
er,我们可以在其中插入“根据新值设置SomeDerivedProperty
”的逻辑。
public readonly record struct FooRecord(string foo)
{
// assign the primary constructor parameter to a field instead
private readonly string foo = foo;
// write the getter and initer of the Foo property explicitly
public string Foo {
get => foo;
init {
foo = value;
SomeDerivedProperty = foo.Split('.').ToList();
}
}
// unfortunately there is a little bit of code duplication here
public readonly IList<string> SomeDerivedProperty = foo.Split('.').ToList();
}
关于c# - 使用 'with' 关键字复制记录结构时重新初始化仅获取属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75679324/