【问题标题】:VB.net Increment variables possible?VB.net 增量变量可能吗?
【发布时间】:2018-05-22 12:34:31
【问题描述】:

我正在尝试找到一种更好的方法来编写此代码,但我不知道如何使代码更简洁。在我过去使用过的其他语言中,我可以使用循环递增变量,而不必将相同的代码应用于多个变量。我想我正在寻找这样的东西,其中变量名称本身正在使用循环进行更改或创建:

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? 这是我当前项目的几个 sn-ps,我想将此逻辑应用于:

1

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

2

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

3

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

【问题讨论】:

  • 数字 3 是你追求的一个重要暗示......
  • google 如何制作数组或列表
  • 嗯 - 为什么thisArray(3) 有效?如果IP(1) 可以工作,那不是很好吗?
  • 我对数组和列表很熟悉,但是如何在循环中应用呢?
  • 这在下面得到了回答,看起来像一个遍历数组或列表的 For 循环就是答案

标签: vb.net loops variables increment do-while


【解决方案1】:

只需将类似的变量存储在 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

【讨论】:

  • 好的,遍历数组或列表的 For 循环。这正是我想要的,谢谢!
  • @user3053446:请注意,如果你得到IP1IP2 字符串变量并且你想保留它们。您还可以使用变量而不是字符串文字来初始化集合。所以 f.e Dim ipArray As String() = { IP1,IP2,IP3,... }
猜你喜欢
  • 2011-06-14
  • 2017-03-09
  • 1970-01-01
  • 1970-01-01
  • 2012-03-19
  • 1970-01-01
  • 1970-01-01
  • 2016-09-03
相关资源
最近更新 更多