c# - 为什么编译器不让我设置只读结构的属性?
问题描述
以下代码无法编译,其中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();
解决方案
推荐阅读
- java - 有没有办法在每次迭代中使用递增数字作为对具有不同数字的方法的调用
- python - ReadFromPubSub->CloudStorage->BigQuery:订阅的大小永远不会减少,而且似乎只有 0.002% 的订阅到达 BigQuery
- microsoft-graph-api - 连接到 Graph API 以获得教育应用程序权限
- javascript - 如何将跨度值传递给laravel控制器
- wordpress - 如何在 WordPress 中添加重写规则以在自定义插件文件夹中提供图像
- azure - 为什么我的多阶段完整 yaml azure devops 管道在移动到模板时会中断?
- c++ - C++如何重载[]运算符并进行函数调用
- r - R:使用公式符号来定义函数,例如 purrr::map(.f=)
- ffmpeg - FFmpeg - 使用 C-API 生成 x264 CBR 视频传输流
- ssis - 在 SSIS 查找转换中设置到 Azure SQL 数据库的连接