c# - 使用 'with' 关键字复制记录结构时重新初始化仅获取属性

标签 c# initialization record with-statement

我有一条记录,其中包含从构造函数参数之一派生的仅获取属性:

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 的 initer 。根据here,您无法控制记录结构的复制方式。 。这样我们就剩下了Fooiniter,我们可以在其中插入“根据新值设置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/

相关文章:

c# - Linq:从两个不同的列表中找到相似的对象

c# - 如何将参数子字符串转换为 C# 中的列类型?

F# 对具有可选字段的记录进行模式匹配

c# - 如果 modelstate 无效,则 Action Filter 不会运行

c# - 在 UML 类图中表示 C# 泛型方法

variables - AS3中初始化类变量的 "proper"位置在哪里

initialization - elf 加载器如何初始化全局变量

c++ - 是否可以用 lambda 初始化变量(当复制 ctor 被删除时)?

actionscript-3 - AS3将媒体文件保存到服务器

python - 使用 Scotch 在 Python 中记录 HTTP