检查某个数字是否存在于给定范围内的替代方法?

时间:2014-10-13 13:28:39

标签: vb.net numbers range

如果我想在某个限制(X - 55)之间检查一个数字(100),那么我需要检查以下条件

If x >= 55 and x <= 100 then
    MsgBox("Number is within the given Range")
Else
    MsgBox("Number is not within the given Range")
End If

是他们检查此内容的最简单方法吗?

BETWEEN中的SQL一样

x BETWEEN 55 and 100

3 个答案:

答案 0 :(得分:2)

您想要一个选择案例陈述:

    Select Case x
        Case 55 To 100
            MsgBox("Number is within the given Range")
        Case Else
            MsgBox("Number is not within the given Range")
    End Select

答案 1 :(得分:1)

另一种方法是创建一个受IComparable<T>接口约束的通用扩展方法。它由所有原始类型(++)实现。

Public Module Extensions

    <Runtime.CompilerServices.Extension()>
    Public Function Between(Of T As IComparable(Of T))(value As T, minimum As T, maximum As T) As Boolean
        Return (value.CompareTo(minimum) >= 0) AndAlso (value.CompareTo(maximum) <= 0)
    End Function

End Module

用法:

If x.Between(55, 100) Then
Else
End If

答案 2 :(得分:0)

我认为他们没有这样的运营商可用,您可以使用SELECT CASE作为替代。

 Dim x As Integer = 72
 Select Case x
    Case 55 To 100
        MsgBox("Number is within the given Range")
     Case Else
        MsgBox("Number is not within the given Range")
 End Select 

或者您可以使用其他方式Enumerable Range

 Dim x As Integer = 72
 Dim rng = Enumerable.Range(200, 200)
 If rng.Contains(x) Then
    MsgBox("Number is within the given Range")
 Else
    MsgBox("Number is not within the given Range")
 End If

两者都不能说是最简单的方法,而是另一种方法