为什么A有效但B无效?
我编写了一个自定义类,我从类似于以下的事件过程实例化它。
Private Sub EventHandler
For intForCounter = 1 to intUserEntry
Dim newObj As New MyClass
newObj.Property
newObj.Method()
Next
End Sub
类本身看起来像这样
Public Property Time As Date
'First attempt:
Dim tmeExec As New Timer
Public Sub Method()
'Second Attempt
Dim tmeExec As New Timer
'A bunch of code for converting a timespan to milliseconds and storing that in intInterval
With tmeExec
.Enabled = True
.Interval = intInterval
End With
AddHandler tmeExec.Tick, AddressOf TickHandler
End Sub
Private Sub TickHandler(ByVal myObj As Object, ByVal myArgs As EventArgs)
Dim tmeSender As Timer = CType(myObj, Timer)
tmeSender.Stop()
'Some code here to do something
End Sub
当我将时间放置在“第一次尝试”位置时,所有内容都会在指定的最后一个时间间隔内触发。
我的期望是,每次实例化一个新对象时,都会用它实例化一个新计时器,因此将实例化放在类中将是正确的方法。事实并非如此。
但我想知道为什么它会这样。知道某件事是如何工作的固然很好,但如果你知道某事为何有效,你就不会再犯同样的错误了。我问了我的教授,但并没有像我想的那样完全理解他的答案。
I have a custom class written, which I instantiate from an event procedure similar to
Private Sub EventHandler
For intForCounter = 1 to intUserEntry
Dim newObj As New MyClass
newObj.Property
newObj.Method()
Next
End Sub
The class itself looks something like this
Public Property Time As Date
'First attempt:
Dim tmeExec As New Timer
Public Sub Method()
'Second Attempt
Dim tmeExec As New Timer
'A bunch of code for converting a timespan to milliseconds and storing that in intInterval
With tmeExec
.Enabled = True
.Interval = intInterval
End With
AddHandler tmeExec.Tick, AddressOf TickHandler
End Sub
Private Sub TickHandler(ByVal myObj As Object, ByVal myArgs As EventArgs)
Dim tmeSender As Timer = CType(myObj, Timer)
tmeSender.Stop()
'Some code here to do something
End Sub
When I had the time placement in the location 'First Attempt', everything fired at the last interval specified.
My expectation is that each time a new object is instantiated, a new timer would have been instantiated with it, and so putting the instantiation in the class would be the right way to go. That's not the case.
But I want to know why it behaves as it does. It's fine to know HOW something works, but if you know WHY something works, you don't make that goof again. I asked my professor, but didn't really understand his answer as fully as I'd like to.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果将计时器的实例化放在方法之外(在“第一次尝试”处),那么您只有一个计时器。每次调用 Method() 时,您只需设置现有计时器的属性并向现有计时器添加新的事件处理程序。
通过将 Timer 实例化移动到 Method() 中,然后每次调用 Method() 时,都会创建一个新的 Timer 对象。
If you place the instantiation of the Timer outside the Method (at 'First attempt'), then you only have a single timer. Each time you call Method(), you are just setting the properties of the existing timer and adding a new event handler to the existing timer.
By moving the Timer instantiation into the Method(), then each time Method() is called, a new Timer object is created.