问题描述
Visual Studio 2019
对私有 _myNum
给出以下建议:改用 auto-property
。起初我很想这样做,去掉这个 private
变量,并让属性带有 private set
。但这并没有提供相同的功能:我想要一个公共属性来公开这条给定的信息,AND只在这个数据可以存在的一个地方set - 构造函数,因此是 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 建议您使用只读属性来简化和/或改进基于某些算法编写的代码,这些算法考虑了不同的通用和标准编码技术,以创建干净、精简、健壮和优化的代码。
>这里的目标是替换不做任何其他事情就获取私有字段值的只读属性和私有字段。
因此,如果您接受此案例列表中的相关建议(我在 VS2017 中有几个),如果您选择“Use {{3} }" 在更改代码的建议选项中(其他当然不相关):
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;
}
}
Readonly field vs. readonly property
Which is better between a readonly modifier and a private setter?
但是如果您需要将此数据成员作为属性,例如用于序列化或由 Visual Studio 设计器和助手使用,并且它必须是可写的……如果您使用 C# 9+,则可以使用 What is the difference between a field and a property? 属性:
public class Foo
{
public int MyNum { get; init; }
public Foo (int num)
{
MyNum = num;
}
}
此外,在 C# 9 之前,没有 get-only 自动属性,将属性与私有字段结合,并删除 Visual Studio 重构助手建议,而无需禁用此模块,您可以简单地使用经典的 getter避免 Visual Studio 代码重构建议的方法:
public class Foo
{
private readonly int _myNum;
public int GetMyNum() => _myNum;
public Foo(int num)
{
_myNum = num;
}
}