C#很简单。如果您有以下代码,则不会有任何意外:
static void Main(string[] args)
{
Console.WriteLine(Test(null, null,null,null));
}
static bool Test(int? firstLeft, int? firstRigt, int? secondLeft, int? secondRight)
{
return firstLeft == firstRigt && secondLeft == secondRight;
}
显然会打印True
作为结果。让我们尝试在VB中做这样的事情:
Sub Main()
Console.WriteLine(Test(Nothing,Nothing,Nothing,Nothing))
End Sub
Function Test(FirstLeft As Integer?, FirstRight As Integer?, SecondLeft As Integer?, SecondRight As Integer?) As Boolean
Return FirstLeft = FirstRight AndAlso SecondLeft = SecondRight
End Function
你能猜出结果会是什么吗? True
?错误。 False
?错误。结果将是InvalidOperationException
。
那是因为可以为空的比较结果的类型不是Boolean
,而是Boolean?
。这意味着,如果比较的任何一方都有Nothing
,则比较结果将不是True
或False
,而是Nothing
。难怪当你试图将它与其他比较结果结合起来时,它不会很好。
我想学习在VB中重写此函数的最惯用的方法。这是我能做的最好的事情:
Function Test(FirstLeft As Integer?, FirstRight As Integer?, SecondLeft As Integer?, SecondRight As Integer?) As Boolean
'If one value has value and the other does not then they are not equal
If (FirstLeft.HasValue AndAlso Not FirstRight.HasValue) OrElse (Not FirstLeft.HasValue AndAlso FirstRight.HasValue) Then Return False
'If they both have value and the values are different then they are not equal
If FirstLeft.HasValue AndAlso FirstRight.HasValue AndAlso FirstLeft.Value <> FirstRight.Value Then Return False
'Ok now we are confident the first values are equal. Lets repeat the excerise with second values
If (SecondLeft.HasValue AndAlso Not SecondRight.HasValue) OrElse (Not SecondLeft.HasValue AndAlso SecondRight.HasValue) Then Return False
If SecondLeft.HasValue AndAlso SecondRight.HasValue AndAlso SecondLeft.Value <> SecondRight.Value Then Return False
Return True
End Function
这很有效,但是看过这段代码的C#版本后,我无法感觉它可以更简单地实现。在这种特殊情况下,只比较了两对,在其他情况下可能会有两对以上,并且上面的代码变得更加冗长,并且您不得不提取一种比较两个值的方法,这感觉就像是一种过度杀伤。
比较VB中可空值的更惯用的方法是什么?
答案 0 :(得分:3)
Function Test(FirstLeft As Integer?, FirstRight As Integer?, SecondLeft As Integer?, SecondRight As Integer?) As Boolean
'Note the HasValue are both false, this function will return true
Return Nullable.Equals(FirstLeft, FirstRight) AndAlso Nullable.Equals(SecondLeft, SecondRight)
End Function