VB.Net: test multiple values for equality?

自闭症网瘾萝莉.ら 提交于 2019-12-22 08:38:04

问题


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.


回答1:


If val1 = valN AndAlso val2 = valN AndAlso ... Then
End If

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




回答2:


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:


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


来源:https://stackoverflow.com/questions/686485/vb-net-test-multiple-values-for-equality

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