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中,什么是比较可空值的更加惯用的方式?