使用C#丢弃运算符获取方法返回值是否有意义? [英] Is there a point to using the C# discard operator for method return values?

查看:36
本文介绍了使用C#丢弃运算符获取方法返回值是否有意义?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

我不完全理解为什么这很重要,对于Fluent API样式代码来说,这似乎还是错误的.

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

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

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

解决方案

摘录自

您还禁用源文件顶部的警告:

您还

Visual Studio 2019's code analysis and code suggestions started to highlight every line of code where I call a method that returns a value but don't use that value at all and tells me to use the discard operator _.

I don't fully understand why that matters and it even seems wrong for Fluent API style code.

Is there a functional difference between the two following lines?

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

Would it matter more if the return value is a reference? If not, Is there a way to globally disable this inspection?

解决方案

Excerpt from 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.

All the code analysis are done to help improve overall coding. Sometimes we write quick methods early in a project that returns a simple value. During refactor we stop using such variable for whatever reason. The code analysis is just pointing that out. And it's up to you as a developer to say, hey let me refactor the method to NOT return variable because we don't need it. It's all a matter of development style on your team.

The verify your issue, I was running VS2019 16.0.0 Preview 5.0 and the issue was there.

Following the comment made by @MartinUllrich, I upgraded to release 16.1.0 Preview 2.0. The warning have disappears. You can also disable the warning using #pragma directive

You also disable the warning at the top of the source file:

You also suppress warnings for the whole project.

这篇关于使用C#丢弃运算符获取方法返回值是否有意义?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆