C#您是否需要检查某物是否具有值以及某物是否大于0? [英] c# do you need to check if something has a value and if something is greater than 0?

查看:68
本文介绍了C#您是否需要检查某物是否具有值以及某物是否大于0?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从事项目工作,编码人员会在检查中做很多事情.首先,他检查可为null的int是否具有值,然后检查其是否大于0.为什么?为什么要进行两次检查,如果一项检查(如果大于0)是否足够?因为空值不大于0,所以...是多余的吗?

Working on a project and the coder does this a lot in his checks. First he checks if the nullable int has a value, and then he checks if its greater than 0. Why? Why make two checks if one check - if it is greater than 0 - should be sufficient? Because nulls are not greater than 0 so ...Is that redundant?

我不确定这是否是我在这里要问的问题,但我不知道如何在Google搜索中用词写出来,所以也许我不知道该程序员会做些什么.

Wasn't sure if this was something I'd ask here but I wouldn't know how to word it in a google search so maybe I don't know something that this programmer does.

推荐答案

该代码可能是多余的.

如果我是int?,则:

if (i.HasValue && i.Value > 0)

等效于:

if (i > 0)

来自 MSDN :

当您对可为空的类型执行比较时,如果其中一个可为空的类型的值是null,而另一个不是,则所有比较的结果均为false,除了!=(不相等).重要的是不要假设因为特定的比较返回false,相反的情况返回true.在下面的示例中,10不大于,小于或等于null.只有num1!= num2的计算结果为true.

When you perform comparisons with nullable types, if the value of one of the nullable types is null and the other is not, all comparisons evaluate to false except for != (not equal). It is important not to assume that because a particular comparison returns false, the opposite case returns true. In the following example, 10 is not greater than, less than, nor equal to null. Only num1 != num2 evaluates to true.

这篇关于C#您是否需要检查某物是否具有值以及某物是否大于0?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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