在VB.NET中这两种返回值的方法有什么区别?
使用退货声明:
Public Function Foo() As String
Return "Hello World"
End Function
Run Code Online (Sandbox Code Playgroud)
使用作业:
Public Function Foo() As String
Foo = "Hello World"
End Function
Run Code Online (Sandbox Code Playgroud)
我正在使用第一个,然后我看到有人使用第二个.我想知道使用第二个是否可以获得一个好处.
想一想:
Public Function Foo() As String
Foo = "Hello World"
OtherFunctionWithSideEffect()
End Function
Run Code Online (Sandbox Code Playgroud)
.
Public Function Foo() As String
Return "Hello World"
OtherFunctionWithSideEffect()
End Function
Run Code Online (Sandbox Code Playgroud)
现在你能看出区别吗?
在实践中,现代VB.Net几乎总是更喜欢后一种风格(Return).
在LinqPad中测试:
Public Function myString() As String
Return "Hello World"
End Function
Public Function myString2() As String
myString2 = "Hello World"
End Function
Run Code Online (Sandbox Code Playgroud)
这是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
Run Code Online (Sandbox Code Playgroud)
所以在某种意义上,IL会增加两条线,但我认为这是一个很小的差异.
两者都是有效的,但如果您想通过函数返回部分路径,则Return必须添加保存Exit Function,因此最好:
If param.length=0 then
Msgbox "Invalid parameter length"
Return Nothing
End If
Run Code Online (Sandbox Code Playgroud)
与之比较:
If param.length=0 then
Msgbox "Invalid parameter length"
Foo = Nothing
Exit Function
End If
Run Code Online (Sandbox Code Playgroud)
另外,如果您Return决定更改函数的名称,则不必记住右键单击“重命名”将 Foo 的所有实例重命名为 FooNew。