如何缩短此代码?

时间:2013-09-04 22:43:32

标签: vb.net

Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick

    If Label1.Text.Length = 13 Then
        Label1.Text = "Working magic."
    ElseIf Label1.Text.Length = 14 Then
        Label1.Text = "Working magic.."
    ElseIf Label1.Text.Length = 15 Then
        Label1.Text = "Working magic..."
    ElseIf Label1.Text.Length = 16 Then
        Label1.Text = "Working magic"
    End If

End Sub

代码基本上充当渐进式字符串,其中每500毫秒一个点将添加到字符串,直到它重置的3个点。

如果我想做更多的点,那么自动化这个过程会很好,而不是编写无限数量的代码行。

6 个答案:

答案 0 :(得分:2)

伪代码:

len = Label1.Text.Length - 12
str = "Working magic"

while(len>0 && len<4){
    str = str & "."
    len--;
}
Label1.Text = str

答案 1 :(得分:2)

如果您想缩短代码,可以执行以下操作:

Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
        (Label1.text += ".").Replace("....","")
End Sub

然而,我确信较短并不总是更好!

编辑:抱歉,我的思绪直接转到c#,这里有一些VB ::

Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
         Label1.text = (Label1.text + ".").Replace("....","")            
End Sub

答案 2 :(得分:1)

考虑到行中可变点数的伪代码。

final NUM_DOTS = 3  //this is your variable number of dots
len = Label1.Text.Length - 12
str = "Working magic"
numDots = NUM_DOTS

while(len){
    if (numDots == 0) {
        str = str.substring(0, str.length-NUM_DOTS);
        numDots = NUM_DOTS;
    }
    else {
        str = str & "."
        len--;
        numDots--;
    }
}
Label1.Text = str

答案 3 :(得分:1)

简单,控制台应用程序演示

Module Module1

   Sub Main()
    Console.WriteLine(Magic(New String("A"c, 13).Length))
    Console.WriteLine(Magic(New String("A"c, 14).Length))
    Console.WriteLine(Magic(New String("A"c, 15).Length))
    Console.WriteLine(Magic(New String("A"c, 16).Length))
    Console.Read()

End Sub

Private Function Magic(ByVal len As Integer) As String
    Dim result = "Working magic"
    Select Case len
        Case 13 To 15
            result = result & New String("."c, len - 12)
    End Select

    Return result
End Function

End Module

答案 4 :(得分:1)

请考虑使用此处生成的动画GIF:http://www.ajaxload.info/

尝试Google搜索以获取更多选项:“GIF动画生成器”

只需在图片框中使用GIF,然后使用.Enable / .Visible进行管理。

如果主线程忙,动画可能会停止 - 对于上述情况也可能是这样。

答案 5 :(得分:0)

保持要打印的点数作为全局变量,然后在每次调用timer事件时递增该值,并在达到上限时重置它。

根据当前计数创建一串点,并将其附加到静态标签

Private dotCount As Integer = 0
Const MAX_DOTS = 3 


Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
    if dotCount > MAX_DOTS Then
        dotCount = 0
    End If
    Label1.Text = "Working magic" & new String(".", dotCount)
    dotCount = dotCount + 1
End Sub

如果要打印更多点,只需更改用作上限的常量(MAX_DOTS)