VB.Net: test multiple values for equality?

大憨熊 提交于 2019-12-05 18:42:47
If val1 = valN AndAlso val2 = valN AndAlso ... Then
End If

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

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

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
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!