我试图找到一种更好的方法来编写这段代码,但我无法弄清楚如何使这个更清洁。在我过去使用的其他语言中,我能够使用循环增加变量,而不必将相同的代码应用于多个变量。我想我正在寻找这样的东西,其中变量名本身正在被改变或使用循环创建:
Dim IP0 As String = ""
While IP0 < 5
IP0 = IP0.Remove(index).Trim
index = IP2.IndexOf(" "c)
IP0 = IP0 + 1
End While
在上面的例子中,我希望“+1”实际上添加到变量本身。因此“IP0”将变为“IP1”,然后变为“IP2”,依此类推。这显然没有编译,有没有办法做到这一点是VB.net? 以下是我当前项目的几个片段,我想将此逻辑应用于:
Dim IP1, IP2, IP3, IP4, IP5, IP6, IP7, IP8, IP9 As String
IP1 = IP1.Remove(index).Trim
index = IP2.IndexOf(" "c)
IP2 = IP2.Remove(index).Trim
index = IP3.IndexOf(" "c)
IP3 = IP3.Remove(index).Trim
index = IP4.IndexOf(" "c)
IP4 = IP4.Remove(index).Trim
index = IP5.IndexOf(" "c)
IP5 = IP5.Remove(index).Trim
index = IP6.IndexOf(" "c)
IP6 = IP6.Remove(index).Trim
index = IP7.IndexOf(" "c)
IP7 = IP7.Remove(index).Trim
index = IP8.IndexOf(" "c)
IP8 = IP8.Remove(index).Trim
index = IP9.IndexOf(" "c)
IP9 = IP9.Remove(index).Trim
Using writer As StreamWriter = New StreamWriter("C:\tempFiles\bigBatch.bat")
writer.Write(
"ping -a " & IP1 & " -n 1 > c:\tempFiles\IP1.txt" & vbNewLine &
"ping -a " & IP2 & " -n 1 > c:\tempFiles\IP2.txt" & vbNewLine &
"ping -a " & IP3 & " -n 1 > c:\tempFiles\IP3.txt" & vbNewLine &
"ping -a " & IP4 & " -n 1 > c:\tempFiles\IP4.txt" & vbNewLine &
"ping -a " & IP5 & " -n 1 > c:\tempFiles\IP5.txt" & vbNewLine &
"ping -a " & IP6 & " -n 1 > c:\tempFiles\IP6.txt" & vbNewLine &
"ping -a " & IP7 & " -n 1 > c:\tempFiles\IP7.txt" & vbNewLine &
"ping -a " & IP8 & " -n 1 > c:\tempFiles\IP8.txt" & vbNewLine &
"ping -a " & IP9 & " -n 1 > c:\tempFiles\IP9.txt" & vbNewLine)
End Using
Dim IP1, IP2, IP3, IP4, IP5, IP6, IP7, IP8, IP9 As String
IP1 = thisArray(3).Trim
IP2 = thisArray(4).Trim
IP3 = thisArray(5).Trim
IP4 = thisArray(6).Trim
IP5 = thisArray(7).Trim
IP6 = thisArray(8).Trim
IP7 = thisArray(9).Trim
IP8 = thisArray(10).Trim
IP9 = thisArray(11).Trim
答案 0 :(得分:4)
只需将类似的变量存储在String()
或List(Of String)
Dim ipList As New List(Of String) From {"IP1", "IP2", "IP3", "IP4", "IP5", "IP6", "IP7", "IP8", "IP9"}
For i As Int32 = 0 To ipList.Count - 1
Dim ip = ipList(i)
Dim indexOfSpace = ip.IndexOf(" "c)
If indexOfSpace >= 0 Then ipList(i) = ip.Remove(indexOfSpace)
Next