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;
}
Run Code Online (Sandbox Code Playgroud)
显然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
Run Code Online (Sandbox Code Playgroud)
你能猜到会是什么结果吗?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
Run Code Online (Sandbox Code Playgroud)
这行得通,但在看过这段代码的 C# 版本后,我无法动摇它可以更简单地实现的感觉。在这种特殊情况下,只比较两对,在其他情况下可能会超过两对,上面的代码变得更加冗长,你不得不提取一种比较两个值的方法,这感觉有点矫枉过正。
在 VB 中比较可空值的更惯用方法是什么?
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
Run Code Online (Sandbox Code Playgroud)

| 归档时间: |
|
| 查看次数: |
427 次 |
| 最近记录: |