VB.Net: test multiple values for equality?

2019-05-07 01:45发布

How do you test multiple values for equality in one line? Basically I want to do

if (val1 == val2 == val3 == ... valN)

but in VB.Net.

3条回答
我只想做你的唯一
2楼-- · 2019-05-07 02:38

If you have a lot of values to test and do this very often, you could write you a helper like this:

Public Function AllTheSame(ByVal ParamArray values() As Object) As Boolean
    For index As Integer = 1 To values.Length - 1
        If values(0) <> values(index) Then Return False
    Next
    Return True
End Function

<Fact()> Public Sub testAllTheSame()
    Assert.True(AllTheSame("Test"))
    Assert.True(AllTheSame("Test", "Test"))
    Assert.True(AllTheSame("Test", "Test", "Test"))

    Assert.True(AllTheSame(1234))
    Assert.True(AllTheSame(1234, 1234, 1234))

    Assert.False(AllTheSame("Test", "Test2"))
    Assert.False(AllTheSame("Test", "Test", "Test3"))

    Assert.False(AllTheSame(1234, 1234, 987))
End Sub
查看更多
放荡不羁爱自由
3楼-- · 2019-05-07 02:43
If val1 = valN AndAlso val2 = valN AndAlso ... Then
End If

This can get cumbersome when testing more than a few values.

查看更多
叛逆
4楼-- · 2019-05-07 02:51

There is no way to chain them together like that. You need to break it up into pair'd comparisions linked by AndAlso

if val1 = val2 AndAlso val2 = val3 AndAlso val1 = val3 Then
查看更多
登录 后发表回答