-1

我想知道是否有办法通过函数调用计时器。这个函数本身是通过一个在表单加载时激活的自动计时器调用的。

Function callTimer(ByRef var1 As Integer, ByVal var2 As Integer)
    'statements()
    Media.SystemSounds.Beep.Play() 'to ensure that it is called
    Call otherFunction(ByRef var3 As Integer) <-- how do you do this??
    Return var1
End Function

我想知道如何做到这一点。当我尝试这个或类似的东西时,VB给了我一个错误。

谢谢大家!

4

2 回答 2

1

问题是您正在定义方法参数,而不是设置它们。

您需要传递一个值,例如:

Call otherFunction(var2) 
于 2012-07-29T22:44:22.383 回答
0

@competent_tech 的意思是你在一个函数中定义一个函数,这是非法的。您想调用该函数,而不是定义它。这方面的一个例子是这样的:

Shared _timer As Timer 'this is the timer control

Function callTimer(ByRef var1 As Integer, ByVal var2 As Integer)
    Media.SystemSounds.Beep.Play() 'to ensure that it is called
    Dim testInt As Integer
    testInt = 4
    Call otherFunction(testInt) '<-- this calls otherFunction and passes testInt
    Return var1
End Function

Function otherFunction(ByRef var3 As Integer)
    StartTimer(var3) ' this will start the timer and set when the timer ticks in ms
                ' (e.g. 1000ms = 1 second)
End Function

'this starts the timer and adds a handler. The handler gets called every time 
'the timer ticks
Shared Sub StartTimer(ByVal tickTimeInMilliseconds As Integer)
    _timer = New Timer(tickTimeInMilliseconds)
    AddHandler _timer.Elapsed, New ElapsedEventHandler(AddressOf Handler)
    _timer.Enabled = True
End Sub
'this is the handler that gets called every time the timer ticks
Shared Sub Handler(ByVal sender As Object, ByVal e As ElapsedEventArgs)
    ' . . . your custom code here to be called every time the timer tickets
End Sub

看起来你可能对调用函数和定义函数有点困惑。在你可以使用一个函数之前,它必须被定义,就像我上面的示例代码一样。

要更好地处理的另一件事是ByRefByVal的使用。ByRef 传递对内存中地址的引用。这意味着对函数内变量的任何更改都将在函数外部持续存在。但是,ByVal 不会在函数之外持续存在,并且在传递给函数之前的值将与函数调用之后的值相同。这是一个例子:

Sub Main()
    Dim value As Integer = 1

    ' The integer value doesn't change here when passed ByVal.
    Example1(value)
    Console.WriteLine(value)

    ' The integer value DOES change when passed ByRef.
    Example2(value)
    Console.WriteLine(value)
End Sub

'any Integer variable passed through here will leave unchanged
Sub Example1(ByVal test As Integer)
    test = 10
End Sub

'any Integer variable passed through here will leave with a value of 10
Sub Example2(ByRef test As Integer)
    test = 10
End Sub

结果:

测试 = 1

测试 = 10

此 ByRef/ByVal 示例可在此链接中查看。如果您仍然感到困惑,则值得进一步研究。

编辑:此编辑包括有关在 VB.NET 中调用计时器的信息。

于 2012-07-31T13:17:14.163 回答