【问题标题】:Difference between "FunctionName = value" and "Return value" in VB.NET?VB.NET中“FunctionName = value”和“Return value”的区别?
【发布时间】:2013-09-20 12:41:01
【问题描述】:

在 VB.NET 函数中,您可以通过两种方式返回值。例如,如果我有一个名为“AddTwoInts”的函数,它接受两个 int 变量作为参数,将它们相加并返回值,我可以将函数编写为以下之一。

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

我的问题是:两者之间有什么区别,或者有理由使用一个而不是另一个?

【问题讨论】:

标签: vb.net


【解决方案1】:

在您的示例中,没有区别。但是,赋值运算符并没有真正退出函数:

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】:

    您的示例中,两者没有区别。选择第一种的唯一真正原因是它与其他语言相似。其他语言不支持第二个示例。

    正如已经指出的,对函数名的赋值不会导致函数返回。

    两个示例生成的 IL 将是相同的。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-02-27
      • 2015-10-12
      • 1970-01-01
      • 2012-06-26
      • 2013-08-31
      • 1970-01-01
      相关资源
      最近更新 更多