4

我要做的是检查一个值是否与两个数字之一匹配(并且很容易添加到要比较的数字中)。而不是做一个冗长的方式,例如:

If Number = 1 Or Number = 2 Then ...

我正在尝试做这样的事情:

If Number In (1,2) Then...

由于该In运算符在 VB 中不可用,因此我尝试了以下代码:

Protected SectionID As Integer = HttpContext.Current.Request.QueryString("sectionid")
Protected PageID As Integer = HttpContext.Current.Request.QueryString("pageid")

Protected Sub HotspotsLV_ItemDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.ListViewItemEventArgs) Handles HotspotsLV.ItemDataBound
    Dim SecondLineHolder As HtmlControl = e.Item.FindControl("SecondLineHolder")
    Select Case True
        Case New String("2", "3").Contains(SectionID) : SecondLineHolder.Attributes("style") = "color:#21720B"
        Case New String("8", "12").Contains(PageID) : SecondLineHolder.Attributes("style") = "color:#1B45C2"
    End Select
End Sub

我发现这仅在SectionID2 或PageID8 时有效。如果SectionID是 3 或PageID12,则它不起作用。为什么会这样,我能做些什么来解决这个问题?谢谢。

4

3 回答 3

3

经过一番玩耍,我设法找到了一个不错的解决方案:

Select Case True
    Case Array.IndexOf(New Integer() {2, 3}, SectionID) > -1 : SecondLineHolder.Attributes("style") = "color:#21720B"
    Case Array.IndexOf(New Integer() {8, 12}, PageID) > -1 : SecondLineHolder.Attributes("style") = "color:#1B45C2"
End Select
于 2011-07-14T16:11:52.587 回答
2
Dim Numbers() As Integer = {1, 2}
If Numbers.Any(Function(i) i = Number) Then
于 2011-07-14T15:48:05.790 回答
1

您正在创建一个String实例而不是数组。尝试将其更改为:

Protected SectionID As Integer = HttpContext.Current.Request.QueryString("sectionid")
Protected PageID As Integer = HttpContext.Current.Request.QueryString("pageid")

Protected Sub HotspotsLV_ItemDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.ListViewItemEventArgs) Handles HotspotsLV.ItemDataBound
    Dim SecondLineHolder As HtmlControl = e.Item.FindControl("SecondLineHolder")
    Dim sections As Integer() = New Integer(){2,3}
    Dim pages As Integer() = New Integer(){8,12}
    Select Case True
        Case sections.Contains(SectionID) : SecondLineHolder.Attributes("style") = "color:#21720B"
        Case pages.Contains(PageID) : SecondLineHolder.Attributes("style") = "color:#1B45C2"
    End Select
End Sub

如果您使用Option Strict On,则类型不匹配将突出显示。在您的初始代码New String("2", "3")中,将创建一个值为222.

编辑

对于 3.5 之前的 .Net 版本,该Contains方法将不可用。可以使用以下方法模仿IndexOf

Array.IndexOf(sections, SectionID) > -1
' Equivalent to sections.Contains(SectionID)
于 2011-07-14T15:49:54.403 回答