7

VB.NET 関数では、2 つの方法で値を返すことができます。たとえば、2 つの int 変数をパラメーターとして受け取る "AddTwoInts" という関数があり、それらを加算して値を返す場合、次のいずれかの関数を記述できます。

1) 「戻る」:

Function AddTwoInts(ByVal intOne As Integer, ByVal intTwo As Integer) As Integer
    Return (intOne + intTwo)
End Function

2) 「関数 = 値」:

Function AddTwoInts(ByVal intOne As Integer, ByVal intTwo As Integer) As Integer
    AddTwoInts = (intOne + intTwo)
End Function

私の質問は次のとおりです。この 2 つに違いはありますか、またはどちらか一方を使用する理由はありますか?

4

2 に答える 2

12

あなたの例では、違いはありません。ただし、代入演算子は実際には関数を終了しません。

Function AddTwoInts(ByVal intOne As Integer, ByVal intTwo As Integer) As Integer
    Return (intOne + intTwo)
    Console.WriteLine("Still alive") ' This will not be printed!
End Function


Function AddTwoInts(ByVal intOne As Integer, ByVal intTwo As Integer) As Integer
    AddTwoInts = (intOne + intTwo)
    Console.WriteLine("Still alive") ' This will  be printed!
End Function

移行を支援するために VB6 から継承された古い言語機能であるため、2 番目の形式は使用しないでください。

于 2013-09-20T12:43:47.123 に答える
0

あなたの例では、2つの間に違いはありません。最初の言語を選択する唯一の本当の理由は、それが他の言語に似ているということです。他の言語は 2 番目の例をサポートしていません。

指摘されているように、関数名への代入は関数からの戻りを引き起こしません。

2 つの例で生成される IL は同じになります。

于 2013-09-20T13:49:11.660 に答える