简体   繁体   English

如何在VB.NET中声明嵌套函数?

[英]How do I declare a nested function in VB.NET?

How would I declare a nested function in VB.NET? 如何在VB.NET中声明嵌套函数? For example, I want to do something like this: 例如,我想做这样的事情:

Function one()
    Function two()
    End Function
End Function

However, this statement is invalid in VB.NET because of unclosed function. 但是,由于未关闭功能,该语句在VB.NET中无效。

Are you asking how to write a lambda expression ? 您是否在问如何编写lambda表达式

A lambda expression is a function or subroutine without a name that can be used wherever a delegate is valid. Lambda表达式是不带名称的函数或子例程,可在委托有效的任何地方使用该表达式。 Lambda expressions can be functions or subroutines and can be single-line or multi-line. Lambda表达式可以是函数或子例程,并且可以是单行或多行。 You can pass values from the current scope to a lambda expression. 您可以将值从当前范围传递到lambda表达式。

You create lambda expressions by using the Function or Sub keyword, just as you create a standard function or subroutine. 您可以使用Function或Sub关键字来创建lambda表达式,就像创建标准函数或子例程一样。 However, lambda expressions are included in a statement. 但是,lambda表达式包含在语句中。

For example, the following code will print "Hello World!": 例如,以下代码将打印“ Hello World!”:

Dim outputString As Action(Of String) = Sub(x As String)
                                            Console.WriteLine(x)
                                        End Sub
outputString("Hello World!")

For more examples, see here: VB.NET Lambda Expression 有关更多示例,请参见此处: VB.NET Lambda表达式

As you noted, this is not possible. 如您所述,这是不可能的。

You have several options 您有几种选择

  • have Function two be a private function within the same class, so you can call it from Function one . 由于Function two是同一类中的私有函数,因此可以从Function one调用它。
  • Create a nested class or structure on the class, again private, and call methods on that. 在该类上创建一个嵌套的类或结构(再次是私有的),然后在其上调用方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM