Visual Studio 2019 的代码分析和代码建议开始突出显示我调用返回值但根本不使用该值并告诉我使用丢弃运算符的方法的每一行代码 _
.
我不完全理解为什么这很重要,甚至对于 Fluent API 风格的代码来说似乎是错误的。
以下两行之间是否存在功能差异?
private int SomeMethod() => 0;
...
SomeMethod();
_ = SomeMethod();
...
如果返回值是一个引用会更重要吗?如果没有,是否有办法全局禁用此检查?
最佳答案
Starting with C# 7.0, C# supports discards, which are temporary, dummy variables that are intentionally unused in application code. Discards are equivalent to unassigned variables; they do not have a value. Because there is only a single discard variable, and that variable may not even be allocated storage, discards can reduce memory allocations. Because they make the intent of your code clear, they enhance its readability and maintainability.
所有代码分析都是为了帮助改进整体编码。有时我们在返回简单值的项目早期编写快速方法。在重构期间,我们出于任何原因停止使用此类变量。代码分析只是指出了这一点。作为开发人员,您可以说,嘿,让我重构该方法以不返回变量,因为我们不需要它。这完全取决于您团队的开发风格。
验证您的问题,我运行的是 VS2019 16.0.0 Preview 5.0,问题就在那里。
根据@MartinUllrich 的评论,我升级到 16.1.0 预览版 2.0。警告消失。您还可以禁用警告 using #pragma directive
关于c# - 对方法返回值使用 C# 丢弃运算符是否有意义?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55984923/