.net - 相同的 If() 和 If 产生不同的结果

标签 .net vb.net if-statement

下面两段代码有什么区别?我希望他们返回相同的结果,但他们没有。

在 xml.@Type = "null"的情况下,我希望 PatientMetricTypeID(一个可为空的整数)最终成为 Nothing。

第 1 block :If()

在这种情况下,它最终为 0。看起来 Nothing 被视为整数并转换为 0。我可以理解为什么会发生这种情况但不完全......我想确切地了解如何这行得通,如果有解决方法。

    Dim PatientMetricTypeID As Integer? = If(xml.@Type = "null",
                                 Nothing,
                                 CType([Enum].Parse(GetType(PatientMetricTypes), xml.@Type), Integer))

第 2 block :如果

在这种情况下,它以 Nothing 结束——预期的行为。

    Dim PatientMetricTypeID As Integer?

    If xml.@Type = "null" Then
        PatientMetricTypeID = Nothing
    Else
        PatientMetricTypeID = CType([Enum].Parse(GetType(PatientMetricTypes), xml.@Type), Integer)
    End If

最佳答案

If 表达式的类型是 Integer,而不是 Integer?

VB.Net 的 Nothing 关键字不等同于 null;相当于C#的default(T),其中T是表达式使用的类型。
报价 MSDN :

Nothing (Visual Basic)

Represents the default value of any data type.

当你写 If(..., Nothing, SomeInteger) 时,如果 If 被键入为 Integer,所以 Nothing 变成 0
要强制将 If 表达式键入为 Integer?,您可以将 Nothing 替换为 New Integer?().

更详细的解释,see my blog .

关于.net - 相同的 If() 和 If 产生不同的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4511608/

相关文章:

c - if/else if 语句中的条件格式是否必须在 C 中匹配?

c# - PrincipalContext.ValidateCredentials 失败,错误为 "The server cannot handle directory requests."

.net - linq to sql和 Entity Framework 的区别

.net - 如何在另一个线程上正确地对调用 UI 方法进行单元测试?

R: "Binning"分类变量

excel - Vlookup 包含其他单元格一部分的单元格,但不是那么简单

.net - Entity Framework 代码第一个自加入, 'Multiplicity is not valid in Role'

c - VB在3DES加密后无法检索字符串

vb.net - 使用Visual Studio的ArcGIS 10.2调试

vb.net - 在动态创建的子菜单项上添加单击事件