首页 > 解决方案 > 为什么编译器不让我设置只读结构的属性?

问题描述

以下代码无法编译,其中CS1612 Cannot modify the return value of 'S2.S1' because it is not a variable

void Main()
{
    var s2 = new S2();
    s2.S1.Field = 1; //error on this line
}

readonly struct S1
{
    public readonly int Field { set { } }
}

readonly struct S2
{
    readonly S1 s1;
    public readonly S1 S1 => s1;
}

如果结构不是readonly,我理解为什么编译器不会让,但现在它们是readonly,访问该属性是完全安全的。

请不要将涉及非结构的问题标记为重复readonly- 对于那些在返回值上更改字段确实没有意义的问题,因为结构只是一个副本。

更重要的是,以下工作正常:

void Main()
{
    var s2 = new S2();
    s2.s1.Field = 1; //accessing the field here instead of the property
}

readonly struct S1
{
    public readonly int Field { set { } }
}

readonly struct S2
{
    public readonly S1 s1;
    public readonly S1 S1 => s1;
}

为什么编译器不让我的第一个例子?

(这是一个最小的、可重现的例子。在我的现实生活中,S1包装了一个类,并具有委托给包装类的属性,我看不出有什么理由C#阻止我。)

根据评论,我将给出一个更清楚的例子来说明为什么readonly应该防止错误:

void Main()
{
    GetS1().Field = 1; //this produces an error
    GetS2().Field = 1; //this compiles fine
}

struct S1
{
    public int Field { set { } }
}

readonly struct S2
{
    public int Field { set { } }
}

S1 GetS1()=>new S1();
S2 GetS2()=>new S2();

标签: c#struct

解决方案


推荐阅读