IF() 函数和可空整数的错误结果? [英] wrong result with IF() function and a nullable integer?

查看:16
本文介绍了IF() 函数和可空整数的错误结果?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望下面的 vb.net 函数返回 Nothing 的值,但它返回的值是 0...

I would expect the following vb.net function to return a value of Nothing, but instead its returning a value of 0...

Public Shared Function GetDefaultTipoSrvTkt() As Integer?
    Dim tsrvDict As New Dictionary(Of Integer, DataRow) 
    GetDefaultTipoSrvTkt = If(IsNothing(tsrvDict) OrElse tsrvDict.Count = 0, Nothing, tsrvDict.First.Key)
End Function

函数的最后一行也可以写成 Return If(IsNothing(tsrvDict) OrElse tsrvDict.Count = 0, Nothing, tsrvDict.First.Key) 但无论如何,为什么是IF() 函数 If(IsNothing(tsrvDict) OrElse tsrvDict.Count = 0, Nothing, tsrvDict.First.Key) 改为返回 0什么都没有?

The last line of the function could also be written as Return If(IsNothing(tsrvDict) OrElse tsrvDict.Count = 0, Nothing, tsrvDict.First.Key) but in any case, why is the IF() function If(IsNothing(tsrvDict) OrElse tsrvDict.Count = 0, Nothing, tsrvDict.First.Key) returning 0 instead of Nothing?

推荐答案

Nothing 在 VB 中可以应用于值类型以及引用类型,并且在所有情况下表示该类型的默认值".因此,例如:

Nothing in VB can be applied to value types as well as reference types, and in all cases means "default value of this type". So, for example:

Dim x As Integer = Nothing
Console.WriteLine(x) ' 0

对于 If() 运算符,VB 必须以某种方式推断返回类型.它查看两个分支,并找出最接近它们的公共类型.在这种情况下,一个分支的类型是 Integer.另一个是 Nothing,它是无类型"的,但它与 Integer 兼容,正如我们之前看到的.因此,If() 的结果类型被推导出为Integer.当 Nothing 在该上下文中返回时,它变为 0.

For If() operator, VB has to deduce the return type somehow. It looks at both branches, and figures out the nearest common type for them. In this case, one branch is of type Integer. Another is Nothing, which is "typeless", but it is compatible with Integer, as we saw earlier. Therefore, the result type of If() is deduced to be Integer. When Nothing is returned in that context, it becomes 0.

显式转换将解决此问题:

An explicit cast will fix this:

GetDefaultTipoSrvTkt = If( _
    IsNothing(tsrvDict) OrElse tsrvDict.Count = 0, _
    CType(Nothing, Integer?), _
    tsrvDict.First.Key)

或者您可以使用替代方法为可空类型指定空值:

or you can use an alternative way to specify the null value for a nullable type:

GetDefaultTipoSrvTkt = If( _
    IsNothing(tsrvDict) OrElse tsrvDict.Count = 0, _
    New Integer?(), _ 
    tsrvDict.First.Key)

这篇关于IF() 函数和可空整数的错误结果?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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