gpt4 book ai didi

c# - 为什么 resharper 建议只读字段

转载 作者:可可西里 更新时间:2023-11-01 08:33:06 26 4
gpt4 key购买 nike

为什么 ReSharper 在下面的示例中为“设置”建议只读字段?

如果我理解正确的话,如果你只在构造函数中更改这个字段,你应该使用 readonly 修饰符,但在我的示例中,我也在同一个类的另一个方法中更改它。

我错过了什么?

public partial class OptionsForm : Form
{
private Settings settings;

public OptionsForm(Settings s)
{
settings = s;
}

private void SaveData()
{
settings.ProjectName = TextBoxProject.Text;
}
}

最佳答案

当引用类型被声明为只读时,指针是不可变的,但它指向的对象不是。这意味着:

  • a reference type data member can be initialized in order to point to an instance of a class, but once this is done it's not possible to make it point to another instance of a class outside of constructors
  • the readonly modifier has no effect on the object the readonly data member points to.

阅读关于此的详细文章

Mark a C# class data member as readonly when it’s read only

关于c# - 为什么 resharper 建议只读字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1565768/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com