测试特定字符VB.NET的字符串

时间:2010-08-04 19:33:12

标签: .net

我有一个具有FTP权限的字符串 - “LRSDCWAN”如果字符串包含相关字符,是否有更有效的检查相关CheckBox的方法?

        If reader.Item("home_perm").Contains("L") Then
            CBoxList.Checked = True
        End If
        If reader.Item("home_perm").Contains("R") Then
            CBoxRead.Checked = True
        End If
        If reader.Item("home_perm").Contains("S") Then
            CBoxSubDir.Checked = True
        End If
        If reader.Item("home_perm").Contains("D") Then
            CBoxDelete.Checked = True
        End If
        If reader.Item("home_perm").Contains("C") Then
            CBoxCreate.Checked = True
        End If
        If reader.Item("home_perm").Contains("W") Then
            CBoxWrite.Checked = True
        End If
        If reader.Item("home_perm").Contains("A") Then
            CBoxAppend.Checked = True
        End If
        If reader.Item("home_perm").Contains("N") Then
            CBoxRename.Checked = True
        End If

感谢。

5 个答案:

答案 0 :(得分:5)

虽然它没有摆脱你的.Contains()问题,但你可以简化逻辑。

如果您注意到,您正在使用:

If reader.Item("home_perm").Contains("L") Then
    CBoxList.Checked = True
End If

您只需说出

即可简化此操作
CBoxList.Checked = reader.Item("home_perm").Contains("L")

您可以为所有复选框执行此操作。它没有解决需要调用contains,但它消除了2/3的代码行。

答案 1 :(得分:2)

编辑.. Doh,我错过了每个角色的不同复选框。

好的,在这种情况下,我会为每个角色使用Dictionary(Of Char, CheckBox)。像这样的东西 - 但在破碎的VB中:)

' Assumes VB10 collection initializers
Dim map As New Dictionary(Of Char, CheckBox) From {
    { "L", CBoxList },
    { "R", CBoxRead },
    { "S", CBoxSubDir },
    { "D", CBoxDelete },
    { "C", CBoxCreate }
}

For Each c As Char In reader.Item("home_perm")
    Dim cb As CheckBox
    If map.TryGetValue(c, cb) Then
        cb.Checked = True
    End If
Next

答案 2 :(得分:2)

正则表达式。

http://msdn.microsoft.com/en-us/library/hs600312(VS.71).aspx

OR

string.indexof方法:

    Dim myString As String = "LRSDCW" 
    Dim myInteger As Integer 
    myInteger = myString.IndexOf("D") // myInteger = 4 
    myInteger = myString.IndexOf("N") // myInteger = -1

对myInteger使用数组并检查数组的每个成员是否为-1以外的值,如果为-1,请不要选中该框。

答案 3 :(得分:0)

您可以将所有比较值放在通用列表中并浏览列表吗?

答案 4 :(得分:0)

CBoxRename.Checked = (New Regex("[LRSDCWAN]").Match(reader.Item("home_perm")).Count > 0) ?

这是非常低效的 - 它每次都是一个相对密集的类的全新实例,因此你可以缓存一个并在需要时重用它,但这样它可以整齐地适合一行。