在Vb.Net中如何比较可空类型?

6

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时,比较的结果不会是TrueFalse,而是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中,什么是比较可空值的更加惯用的方式?


VB.NET和C#在比较可空值时有相同的习惯用法 :) - Fabio
1个回答

10
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

Nullable.Equals

输入图像说明


没错,就是这样。谢谢。 - Andrew Savinykh

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接