2010-08-04 34 views
1

我有一個具有FTP權限的字符串 - 「LRSDCWAN」如果字符串包含相關字符,是否有更有效的方法來檢查相關的CheckBox?特定字符的測試字符串VB.NET

 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

雖然它沒有擺脫您的.Contains()問題,但您可以相當簡化邏輯。

如果你發現,你正在使用:

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

你可以隨便說

CBoxList.Checked = reader.Item("home_perm").Contains("L") 

您可以爲您所有的複選框都這樣做簡化了這一點。它不能解決調用包含的需要,但它消除了2/3的代碼行。

+0

大也許在這裏......如果這是合適的,這也會通過取消選中不在權限列表中的項目來修復OP代碼中可能存在的錯誤。如果OP有意避免不檢查項目,這會導致一個錯誤。 – overslacked 2010-08-04 20:13:09

0

你可以把所有的比較值放在一個通用列表中,然後走這個列表嗎?

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 
+1

我想你忽略了每個值都有一個單獨的複選框 – kmfk 2010-08-04 19:38:39

+0

Doh--沒有發現那個。多煩人。 – 2010-08-04 19:41:09

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,不要選中框。

+0

我不認爲正則表達式實際上可以幫到這裏... – 2010-08-04 19:46:51

+0

也許不是,它只是我的第一個想法檢查字符串,或者,你可以通過string.indexof方法來獲取字母串中的位置,它如果它不退出,它會給-1,但它不會優雅,但它會起作用 – MaQleod 2010-08-04 19:54:05

+0

MaQleod:我不認爲檢查單個字符的遏制是否是一個問題,包含工作正常。問題是重複。我沒有看到如何使用正則表達式*或* IndexOf幫助那裏。 – 2010-08-05 05:26:55

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

這是非常低效 - 這是每次相對密集類的品牌新的實例,所以你可以一個緩存和重用它,如果你想要的,但這種方式正好放進一行。

+0

詛咒。與傳奇人物Jon Skeet犯了同樣的錯誤;所以我不覺得太糟糕。 您可以連接您使用的相同邏輯 Checkbox.Checked = reader.Item(「home_perm」)。Contains(「L」) – 2010-08-04 19:44:21