加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

VB.net中的If()函数之谜

发布时间:2020-12-17 07:24:44 所属栏目:百科 来源:网络整理
导读:我有这个代码: dstCell.CELL_VALUE_INT = If(srcCell.CELL_VALUE_FLOAT IsNot Nothing,Math.Round(CDbl(srcCell.CELL_VALUE_FLOAT)),Nothing) 当srcCell.CELL_VALUE_FLOAT为Nothing时,它会神秘地评估True部分! 有趣的是,正常的If语句正确评估为False部分:
我有这个代码:

dstCell.CELL_VALUE_INT = If(srcCell.CELL_VALUE_FLOAT IsNot Nothing,Math.Round(CDbl(srcCell.CELL_VALUE_FLOAT)),Nothing)

当srcCell.CELL_VALUE_FLOAT为Nothing时,它会神秘地评估True部分!

有趣的是,正常的If语句正确评估为False部分:

If (srcCell.CELL_VALUE_FLOAT IsNot Nothing) Then
    dstCell.CELL_VALUE_INT = Math.Round(CDbl(srcCell.CELL_VALUE_FLOAT))
Else
    dstCell.CELL_VALUE_INT = Nothing
End If

有任何想法吗?

感谢你!

编辑:
CELL_VALUE_FLOAT是Nullable(Of Double),CELL_VALUE_INT是Nullable(整数)

在Quickwatch中,条件将correclty评估为False,但在运行时,If()函数的计算结果为True部分.

解决方法

VB.NET中的任何内容都不完全等于C#中的null
它更像默认值(T),其中T是Type.

' VB:
dim x as DateTime = DateTime.MinValue
If x Is Nothing then
    Console.WriteLine("True")
End if

' C#
var x = DateTime.MinValue
if (x == default(DateTime))
    Console.WriteLine("True");

if (x == null) ' throw a compile time error

dim x as Double = nothing ' x will be 0 (default for Double)

如果希望两个返回值都是相同的类型,则内联构建.所以你真正做的是:

dstCell.CELL_VALUE_INT = If(srcCell.CELL_VALUE_FLOAT IsNot Nothing,Convert.ToDouble(Nothing))

因为false部分内部转换为double
和dstCell.CELL_VALUE_INT将为0而不是任何内容.

试试这个:

dstCell.CELL_VALUE_INT = If(srcCell.CELL_VALUE_FLOAT IsNot Nothing,Ctype(Math.Round(CDbl(srcCell.CELL_VALUE_FLOAT)),Integer?),Nothing)

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读