是否可以在一个函数中包含一个函数?
问题描述:
是否可以在一个函数中包含一个函数?
Is it possible to have a function within a function?
像这样:
Public Class Form1
Private Sub button1_Click(sender As Object, e As EventArgs) Handles button1.Click
Sub anim() Handles form2.Shown
Me.Refresh()
Do Until Me.Location.X = 350
form2.Location = New Point(Me.Location.X + 1, 250)
' System.Threading.Thread.Sleep(0.5)
Loop
form2.close()
End Sub
End Sub
End Class
答
在 VB.NET 中不可能有完全成熟的嵌套函数定义.该语言确实支持看起来很像嵌套函数的多行 lambda 表达式:
It is not possible to have a fully fledged nested function definition in VB.NET. The language does support multi-line lambda expressions which look a lot like nested functions:
Private Sub button1_Click(sender As Object, e As EventArgs) Handles button1.Click
Dim anim =
Sub()
Me.Refresh()
...
End Sub
End Sub
虽然有一些显着差异:
- 不能有
Handles
子句. - 不能是
Implements
或Overrides
. - 命名的是 lambda 的实例,而不是
Sub
定义. - 在这种情况下,
anim
实际上是一个委托,而不是一个函数.
- Cannot have a
Handles
clause. - Cannot be
Implements
orOverrides
. - The instance of the lambda is named, not the
Sub
definition. - In this case
anim
is actually a delegate and not a function.