如何指示何时故意忽略返回值 [英] How to indicate when purposely ignoring a return value

查看:41
本文介绍了如何指示何时故意忽略返回值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在某些使用 C/C++ 的情况下,我可以在语法上向编译器指示有意忽略返回值:

In some situations using C/C++, I can syntactically indicate to the compiler that a return value is purposely ignored:

int SomeOperation()
{
    // Do the operation

    return report_id;
}

int main()
{
    // We execute the operation, but in this particular context we
    // have no use of the report id returned.
    (void)SomeOperation();
}

我认为这是一种公平的做法,首先是因为大多数编译器不会在这里生成警告,其次是因为它明确地向未来的开发人员表明,作者有意选择忽略返回.使作者的思路清晰明了.

I find this to be a fair practice, firstly because most compilers won't generate a warning here, and secondly because it explicitly shows to future developers that the author made a conscious choice to ignore the return. It makes the author's trail of thought non ambiguous.

据我所知,C# 编译器不会抱怨隐式忽略返回值,但我想知道是否有类似的约定可以使用,以便向其他开发人员明确指示.

As far as I know, the C# compiler won't complain about implicitly ignored return values, but I would like to know if there's a similar convention to use in order to make a clear indication to other developers.

回应这里有些人质疑该约定的实际使用(或者如果方法具有可能不重要的返回值会显示出糟糕的设计).

In response to some people here who questions the actual use of this convention (or that it would show bad design to have a method with a potentially unimportant return value).

一个现实生活中的 .NET 示例(我可能应该从一开始就基于这个问题)是 Mutex::WaitOne() 重载,它不带参数.只有当互斥锁被安全获取时它才会返回,否则它永远不会返回.布尔值返回值用于其他重载,在这些重载返回时,您可能最终不拥有互斥锁.

A real life .NET example (which I maybe should have based the question on from the start) is the Mutex::WaitOne() overload which takes no arguments. It will only return if the mutex was safely acquired, otherwise it never returns. The boolean return value is for the other overloads where you might end up not being in possession of the mutex when it returns.

因此,根据我的推理,我想在我的多线程代码中指出我已选择忽略返回:

So along my reasoning, I would like to indicate in my multi-threaded code that I have made a choice to ignore the return:

Mutex mtx = new Mutex();
(void)mtx.WaitOne();

因为返回值只能是 true.

推荐答案

我只能想到一种情况,在 C# 中不允许忽略返回值":发生错误时.这应该通过抛出异常来提供,这使得它不可能被忽略.

I can only think of one situation, when a "return value" is not allowed to be ignored in C#: when an error occurred. This should be provided by throwing an exception, which makes it impossible to be ignored.

在其他情况下,忽略返回值是(或更好:必须)完全安全且完全没有臭味.

In other cases, it is (or better: must be) completely safe and not smelly at all to ignore return values.

我仍然看不到重点.为什么要改进代码?您可以通过不将其分配给变量来指定忽略返回值.

I still can't see the point. Why should this improve the code? You specify to ignore the return value by purpose by not assigning it to a variable.

  • 如果您的代码中不需要此值,则一切正常.
  • 如果您需要它,您将无法编写代码.
  • 如果存在必须处理且绝不能隐式忽略的特殊情况,则应抛出异常.
  • 如果被调用的方法没有返回值并且稍后获得返回值,则必须将其设计为不破坏忽略它的现有代码.现有的调用代码不会改变.

我忘记了一个案例吗?

这篇关于如何指示何时故意忽略返回值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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