“退出功能”的必要性

时间:2017-08-03 18:43:34

标签: vbscript return

我是VBScript的新手,并且我了解到VBScript没有return并且要返回值,您可以将值分配给过程的名称。 当我研究如何返回一个值时,我发现两个不同的程序都返回一个值,我不确定它们之间的区别。

Function Test1()
    Dim value
    'Do something'
    If value < 10 Then
        Test1 = value * 2
    Else 
        Test1 = value
    End If
End Function

Function Test2()
    Dim value
    'Do something'
    If value < 10 Then
        Test2 = value * 2
        Exit Function
    Else 
        Test2 = value
        Exit Function
    End If
End Function

当这个程序到达这一行时,似乎Exit Function立即退出程序,但是这行代码的必要性是什么? 我一直在学习其他主要的编程语言,如C#,Java等,在这些编程语言中,一旦程序进入行returnreturn something,程序就会退出该函数/方法,即使之后有模式代码。

这是否意味着,在VBScript中,为其自己的过程的名称赋值为return,但除非您使用Exit Function,否则它仍会继续运行直到过程结束?

2 个答案:

答案 0 :(得分:1)

指定函数的返回值并返回调用者(通过到达函数体的末尾或显式语句)显然是不同的事情。能够清楚地表达两者是专业人士:

>> Function preinc(ByRef i) : i = i + 1 : preinc = i : End Function
>> Function postinc(ByRef i) : postinc = i : i = i + 1 : End Function
>> i = 0
>> WScript.Echo i
>> WScript.Echo preinc(i), i
>> WScript.Echo postinc(i), i
>>
0
1 1
1 2

组合设置值并离开函数(return(x),返回'last'表达式的值)的语言在确定后不允许您进行工作或清理(参见here)返回值。

答案 1 :(得分:0)

如果您想要指示函数立即返回而不是继续该功能,则VBScript需要Exit Function命令。要在VBScript中指定返回值,请使用FUNCTIONNAME=VALUE_TO_RETURN。但是在VBScript中,这种类型的语句不能退出功能(尽管在类C语言中,返回值(return X;)的赋值会立即退出函数。)

例如,假设您正在尝试生成尚不存在的文件名。

Function GenName( ROOT, file )
  targetPath = ROOT & "\" & file.Name
  If Not ofso.FileExists( targetPath ) Then
    ' ASSIGN RETURN VALUE THEN..
    GenName = targetPath
    Exit Function ' __GET OUT OF THE FUNCTION__
    ' If you neglect EXIT FUNCTION here, then
    ' THIS FUNCTION WILL CONTINUE RUNNING TO THE END
    ' OF IT, even though YOU'VE ALREADY ASSIGNED THE FUNCTION
    ' A RETURN VALUE
  End If

  For num = 1 To 10000
    ' append numbers until you find one that doesn't exist or quit
    targetPath = ROOT & "\" & ofso.GetBaseName( file ) & "-" & num & "." & ofso.GetExtensionName( file )
    If Not ofso.FileExists( targetPath ) Then
      GenName = targetPath ' WANTS to be "return targetPath"
      ' but you can't do that in VBSCRIPT. So ASSIGN VALUE to
      ' function name.. AND THEN..
      Exit Function '' MUST EXIT FUNCTION otherwise function
      ' will just continue to run (for loop will keep executing)
      ' else can break loop with EXIT FOR
    End If
  Next
End Function
相关问题