相同的,如果(),如果产生不同的结果 [英] Identical If() and If yield different results
问题描述
在以下code中的两个块有什么区别?我希望他们返回相同的结果,但他们没有。
在情况下的xml。@类型=空,我想PatientMetricTypeID(可为空的整数)最终被什么也没有。
阻止#1:如果()
在这种情况下,它最终为0。它看起来像没有被当作一个整数并转换为0之类的,我可以明白为什么这会发生,但不能完全......我想确切了解这个工程,如果有解决方法。
昏暗PatientMetricTypeID作为整数? = IF(XML。@类型=空,
没什么,
CTYPE([枚举] .Parse(的GetType(PatientMetricTypes),XML。@类型),整数))
阻止#2:如果
在这种情况下,它最终为虚无 - 期望的行为
昏暗PatientMetricTypeID作为整数?
如果XML。@ TYPE =空然后
PatientMetricTypeID =无
其他
PatientMetricTypeID = CTYPE([枚举] .Parse(的GetType(PatientMetricTypes),XML。@类型),整数)
结束如果
在如果
EX pression的类型是整数
,不是整数?
。
VB.Net的没有
关键字不等同于空
;它等同于C#的默认(T)
,其中 T
是前pression用作类型。照片
引用 MSDN :
无(Visual Basic中)
重新presents任何数据类型的默认值
当你写如果(...,没什么,SomeInteger)
,如果如果
的类型是整数
,所以没有
变成 0
。
要强制如果
EX pression被类型为整数?
,可以替换没有
与新的整数?()
。
有关更详细的解释,看我的博客。
What is the difference in the two blocks of code below? I expected them to return the same result, but they don't.
In the case where xml.@Type = "null", I want PatientMetricTypeID (a nullable Integer) to end up being Nothing.
Block #1: If()
In this case, it ends up as 0. It looks like Nothing is being treated as an Integer and converted to 0. I can sort of see why this might happen but not fully... I would like to understand exactly how this works, and if there is a workaround.
Dim PatientMetricTypeID As Integer? = If(xml.@Type = "null",
Nothing,
CType([Enum].Parse(GetType(PatientMetricTypes), xml.@Type), Integer))
Block #2: If
In this case, it ends up as Nothing -- expected behavior.
Dim PatientMetricTypeID As Integer?
If xml.@Type = "null" Then
PatientMetricTypeID = Nothing
Else
PatientMetricTypeID = CType([Enum].Parse(GetType(PatientMetricTypes), xml.@Type), Integer)
End If
The If
expression is of type Integer
, not Integer?
.
VB.Net's Nothing
keyword is not equivalent to null
; it's equivalent to C#'s default(T)
, where T
is the type that the expression is used as.
To quote MSDN:
Nothing (Visual Basic)
Represents the default value of any data type.
When you write If(..., Nothing, SomeInteger)
, if If
is typed as Integer
, so Nothing
turns into 0
.
To force the If
expression to be typed as an Integer?
, you can replace Nothing
with New Integer?()
.
For a more detailed explanation, see my blog.
这篇关于相同的,如果(),如果产生不同的结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!