c# 是否需要检查某物是否有值以及某物是否大于 0?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10212469/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 12:54:32  来源:igfitidea点击:

c# do you need to check if something has a value and if something is greater than 0?

c#if-statement

提问by egucciar

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?

在一个项目上工作,编码员在他的检查中做了很多。首先他检查可空 int 是否有值,然后检查它是否大于 0。为什么?如果一项检查——如果它大于 0——就足够了,为什么要进行两次检查?因为空值不大于 0 所以......这是多余的吗?

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.

不确定这是否是我会在这里问的问题,但我不知道如何在谷歌搜索中用词表达,所以也许我不知道这个程序员所做的事情。

采纳答案by Mark Byers

The code is probably redundant.

代码可能是多余的。

If i is int?then:

如果我是int?那么:

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

is equivalent to:

相当于:

if (i > 0)

From MSDN:

MSDN

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.

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

回答by Ropstah

It might be that the value for the variable has different meanings in that context.

变量的值可能在该上下文中具有不同的含义。

int? someNumber = null; //might mean "there is no value"
int? someOtherNumber = 0; //might mean "the user has selected: 0"

回答by MikeWyatt

Null checking is generally done to prevent exceptions, or to set default values (prior to .NET 4). Checking for zero would be more of a business logic choice, depending on the circumstances.

空检查通常用于防止异常或设置默认值(.NET 4 之前)。根据情况,检查零将更多是一种业务逻辑选择。

回答by StuartLC

You might find that the programmer is used to the following type of checking on reference types before dereferencing them. Given that the the Nullable HasValueis similar in concept to the null check, I guess the pattern 'stuck', even though it is redundant with nullable types.

您可能会发现程序员习惯于在取消引用它们之前对引用类型进行以下类型的检查。鉴于 NullableHasValue在概念上与空检查相似,我猜想模式“卡住”了,即使它对于可空类型是多余的。

if ((myObject != null)  && (myObject.SomeValue > 0))

...

...

回答by hatchet - done with SOverflow

The following:

下列:

class Program {
    static void Main(string[] args) {
        int? i = null;
        if (i > 0) { Console.WriteLine(">0");
        } else {     Console.WriteLine("not >0");
        }
        if (i < 0) { Console.WriteLine("<0");
        } else {     Console.WriteLine("not <0");
        }
        if (i == 0) {Console.WriteLine("==0");
        } else {     Console.WriteLine("not ==0");
        }
        Console.ReadKey();
    }
}

will output

会输出

not >0
not <0
not ==0

without throwing an exception. So the null/HasValue check in this case is redundant. There is one small difference. The following:

不抛出异常。所以在这种情况下 null/HasValue 检查是多余的。有一个小的区别。下列:

(i.HasValue && (i.Value == 0))

is about twice as fast as

大约是两倍

(i == 0)

when i is null although both are so fast it's not an important difference. When i has a value, the two comparisons take about the same amount of time.

当 i 为空时,尽管两者都如此之快,但这并不是重要的区别。当 i 有一个值时,两次比较花费的时间大致相同。

回答by Mayer Spitzer

Since by default an intcannot be nulland its value will be set to 0, the operator of >and <expects to work with valuesand not with nulls, so that's why you must first check if it's null, because it will cause an error if it is null.

由于默认情况下 anint不能是null并且它的值将被设置为0>and的运算符<期望使用values而不是与nulls,所以这就是为什么你必须首先检查它是否是null,因为如果它为空会导致错误。

You can use a logic that will always return an int, even if it's nullit will 'not' return nullbut it will return 0which is the default value, and by using this you can check for null+ >at once.

您可以使用始终返回 的逻辑int,即使null它会“不”返回,null但会返回0默认值,通过使用它,您可以立即检查null+ >

Here are some ways to do it:

以下是一些方法:

int? nullableNum = null;
int number;
number = nullableNum.GetValueOrDefault(); // will return 0 if null
number = nullableNum ?? 0;                // will return 0, or whatever you insert

If you don't know if the nullableNumwill be a nullable typeor not (usually not relevant in C#), then in case it turns out not to be nullable, the nulloperator won't work and nor the GetValueOrDefault()method, so in that case you can castits typeto a nullable intand then check:

如果您不知道nullableNumwill 是否为 a nullable type(在 C# 中通常不相关),那么如果结果不是nullable,则null操作符和GetValueOrDefault()方法都将不起作用,因此在这种情况下,您可以强制转换type到 anullable int然后检查:

number = ((int?)nullableNum) ?? 0