c# - 对方法返回值使用 C# 丢弃运算符是否有意义?

标签 c# .net operator-keyword

Visual Studio 2019 的代码分析和代码建议开始突出显示我调用返回值但根本不使用该值并告诉我使用丢弃运算符的方法的每一行代码 _.

我不完全理解为什么这很重要,甚至对于 Fluent API 风格的代码来说似乎是错误的。

以下两行之间是否存在功能差异?

private int SomeMethod() => 0;
...
SomeMethod();
_ = SomeMethod();
...

如果返回值是一个引用会更重要吗?如果没有,是否有办法全局禁用此检查?

最佳答案

摘自 Microsoft Documentation :

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

Sample with pragma directive

您还可以禁用源文件顶部的警告: enter image description here

你也suppress warnings for the whole project .

suppress for project

关于c# - 对方法返回值使用 C# 丢弃运算符是否有意义?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55984923/

相关文章:

c# - Elmah 仅记录 15 个错误

c# - 在窗口应用程序中写入命令行

c++ - 重载输入/输出运算符,为什么它以这种方式工作而不是另一种方式?

c# - VSTO(文档级): Individual context menu in Excel (right click menu)

c# - 使用 RegisterHotKey 通过 Numpad 注册热键

c# - 如何动态隐藏jqgrid列

.net - Oracle pl/sql中的多线程概念

.net - .NET Framework SDK 和 Targeting pack 之间有什么区别

powershell - PowerShell 比较运算符背后的推理

Python += 与全局变量函数内的 .extend()