Visual Studio IDE0032 推荐有时会是错误的应用吗?

Could Visual Studio IDE0032 recommendation sometimes be the wrong thing to apply?

Visual Studio 2019 对私有 _myNum 给出了以下建议:改为使用 auto-property。起初我很想这样做,摆脱这个 private 变量并让 属性 带有 private set。但是这个 没有给 相同的功能:我想要一个 public 属性 来公开这个给定的信息,AND 到一个可以设置这条数据的地方 - 构造函数,因此是 readonly 关键字。

换句话说,我是对的,这个建议并不总是正确的吗?

public class Foo
{
    public int MyNum { get { return _myNum; } }
    private readonly int _myNum;
    public Foo(int num)
    {
        _myNum = num;
    }
}

应用自动完成建议,代码如下所示:

public int MyNum { get; }

public Foo(int num)
{
    MyNum = num;
}

Visual Studio建议您使用只读属性来简化and/or改进基于某些算法编写的代码,这些算法考虑了不同的通用和标准编码技术来创建干净、精简、健壮和优化的代码。

这里的目标是替换只读的 属性 获取私有字段的值而不做任何其他事情,以及那个私有字段。

因此,如果您接受列表中针对此案例的相关建议(我有几个与 VS2017 相关的建议),如果您 select 选择“在建议选项中使用auto-property”更改代码(其他的肯定不相关):

public class Foo
{
  public int MyNum { get; }
  public Foo (int num)
  {
    MyNum = num;
  }
}

这个建议是正确的,采纳是合适的。

其他建议会产生您在大多数情况下不需要的东西...

如果您打算在 getter 中添加行为,您可以忽略来自 Visual Studio 的建议:

public class Foo
{
  public int MyNum
  {
    get
    {
      return _myNum >= 100 ? 100 : _myNum;
    }
  }
  private readonly int _myNum;
  public Foo(int num)
  {
    _myNum = num;
  }
}

否则如果你想要一个只读数据成员,你可以使用一个只读字段:

public class Foo
{
  public readonly int MyNum;
  public Foo (int num)
  {
    MyNum = num;
  }
}

Which is better between a readonly modifier and a private setter?

What is the difference between a field and a property?

但是如果您需要此数据成员是 属性,例如用于序列化或由 Visual Studio 设计师和助手使用,并且它通常必须是可写的...和如果您使用 C# 9+,则可以使用 init-only 属性:

public class Foo
{
  public int MyNum { get; init; }
  public Foo (int num)
  {
    MyNum = num;
  }
}

此外,在 C# 9 之前,没有 get-only auto-属性,有一个 属性 加上一个私有字段,并删除 Visual Studio 重构助手建议, 在不禁用此模块的情况下,您可以简单地使用经典的 getter 方法来避免 Visual Studio 代码重构建议:

public class Foo
{
  private readonly int _myNum;
  public int GetMyNum() => _myNum;
  public Foo(int num)
  {
    _myNum = num;
  }
}