铸造一空到什么?一空到

2023-09-03 07:28:54 作者:姑娘並好妳的腿@

我今天也参加了这个有趣的讨论,同事。我们是在C#中讨论两件code。

I had this interesting discussion today with a colleague. We were debating two pieces of code in C#.

code片段1:

if(!reader.IsDBNull(2))
{
  long? variable1 = reader.GetInt64(2)
}

code片段2:

Code Snippet 2:

long variable1 = reader.IsDBNull(2) ? (long?) null : reader.GetInt64(2)

问题是:这是一个很好的做法,投空成一个可空长?或者你更愿意使用传统的if语句,以避免铸造可空长。

推荐答案

这位前pressions (类型?)空默认(型)新可空<类型>()最终会被编译成相同的运算codeS:

The expressions (type?)null, default(type?) and new Nullable<type>() end up being compiled into the same opcodes:

        long? x = (long?)null;
        long? y = default(long?);
        long? z = new Nullable<long>();

变成:

    IL_0001: ldloca.s x
    IL_0003: initobj valuetype [mscorlib]System.Nullable`1<int64>
    IL_0009: ldloca.s y
    IL_000b: initobj valuetype [mscorlib]System.Nullable`1<int64>
    IL_0011: ldloca.s z
    IL_0013: initobj valuetype [mscorlib]System.Nullable`1<int64>

在换句话说,如果您正在使用可空类型,您可以自由使用任何版本中,你最喜欢的。但是请注意,你应该尽量避免使用算术可空类型。如果你想从一个条件EX pression返回一个空值,这两个可能的结果必须是可空,如果他们中的一个可以为空。任何其他方式可能导致在这种情况下,一个异常。

In other words, if you are working with nullable types, you are free to use whichever version you like best. Note however, that you should try to avoid arithmetics with nullable types. If you want to return a nullable value from a conditional expression, both possible results must be nullable if one of them can be null. Any other way could cause an exception in that case.

相关推荐