VB.NET函数-返回与分配

VB.NET函数-返回与分配,vb.net,function,Vb.net,Function,在VB.NET中,函数返回值的这两种方式有什么不同 使用Return语句: Public Function Foo() As String Return "Hello World" End Function 使用分配: Public Function Foo() As String Foo = "Hello World" End Function 我在用第一个,然后我看到有人在用第二个。我想知道使用第二个是否有好处。这是基本日遗留下来的遗产 Return将立即离开范围,而赋值

在VB.NET中,函数返回值的这两种方式有什么不同

使用Return语句:

Public Function Foo() As String
    Return "Hello World"
End Function
使用分配:

Public Function Foo() As String
    Foo = "Hello World"
End Function

我在用第一个,然后我看到有人在用第二个。我想知道使用第二个是否有好处。

这是基本日遗留下来的遗产

Return
将立即离开范围,而赋值不会

这样想:

Public Function Foo() As String
    Foo = "Hello World"
    OtherFunctionWithSideEffect()
End Function
vs

现在你能看出区别了吗


在实践中,现代VB.Net几乎总是倾向于后一种样式(
Return

在LinqPad中测试:

Public Function myString() As String    
    Return "Hello World"
End Function

Public Function myString2() As String
    myString2 = "Hello World"
End Function
以下是IL输出:

myString:
IL_0000:  ldstr       "Hello World"
IL_0005:  ret         

myString2:
IL_0000:  ldstr       "Hello World"
IL_0005:  stloc.0     
IL_0006:  ldloc.0     
IL_0007:  ret 

因此,从某种意义上说,IL会再添加两行,但我认为这是一个小的差异。

两者都是有效的,但使用
Return
可以避免添加
Exit Function
,如果您想通过函数部分返回,则最好:

If param.length=0 then
    Msgbox "Invalid parameter length"
    Return Nothing
End If
与之相比:

If param.length=0 then
    Msgbox "Invalid parameter length"
    Foo = Nothing
    Exit Function
End If

另外,如果您使用
Return
,如果您决定更改函数的名称,则不必记住右键单击“重命名”将所有Foo实例重命名为FooNew。

除了其他答案之外,还有一个区别,如下所示:

Public Function Test() As Integer
  Try
    Dim retVal as Integer = 0
    retVal = DoSomethingExceptional()
  Catch ex as Exception ' bad practice, I know
  Finally
  Test = retVal
  End Try
End Function

不能在Finally块中放置返回,但可以在那里指定函数的值。

这实际上是不正确的,因为在第一个函数中,将执行OtherFunctionWithSideEffect,而在第二个函数中则不会执行。这可以被视为选项1的+值。在这种情况下,@chrissie Joel的观点是,在第一个函数中,OtherFunctionWithSideEffect将执行,而在第二个函数中,它将执行not@chrissie1-当然他们是不同的。这就是重点。
Public Function Test() As Integer
  Try
    Dim retVal as Integer = 0
    retVal = DoSomethingExceptional()
  Catch ex as Exception ' bad practice, I know
  Finally
  Test = retVal
  End Try
End Function