gpt4 book ai didi

.net - 如何比较 Vb.Net 中的可空值?

转载 作者:行者123 更新时间:2023-12-02 08:28:14 25 4
gpt4 key购买 nike

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

最佳答案

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

enter image description here

关于.net - 如何比较 Vb.Net 中的可空值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29957324/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com