gpt4 book ai didi

vbscript - VBScript 函数中的变量范围

转载 作者:行者123 更新时间:2023-12-04 03:02:32 28 4
gpt4 key购买 nike

我有一个关于 VBScript 中变量作用域的问题。我知道有以下关键字(来自 autoitscript.com ):

  • Dim = 局部作用域,如果变量名在全局不存在(在这种情况下它重用全局变量!)
  • Global = 强制在全局范围内创建变量
  • Local = 强制在 Local/Function 范围内创建变量

  • 想象一下,我有以下 .vbs 文件:
    Dim strPath

    strPath = "C:\folder"

    DisplayPath strPath

    Sub DisplayPath(strPath) 'Does this strPath get it's own local scope?
    MsgBox strPath
    End Sub

    在函数中:DisplayPath(strPath) , 是 strPath局部变量?或者函数/子是否可以访问 strPath在脚本主要部分的顶部定义为全局变量?

    另外,明确使用 Dim 有什么意义?与仅在我使用时定义变量相比,这在脚本语言中是可能的吗?

    最佳答案

    strPathDisplayPath过程将是一个新变量,但不是出于您期望的原因,您的代码存在微妙的问题,这会使问题变得模糊。

    打电话时Sub过程 VBScript 语法不包括括号。例如:-

    Sub MyProc(Param1, Param2)
    '' # Do stuff
    End Sub

    MyProc("Hello", "World")

    以上将导致语法错误。它应该被称为:-
    MyProc "Hello", "World"

    现在当只有一个参数时不会发生语法错误。这是因为括号的另一种用法是作为表达式的一部分,例如'(a + b) * c'。如果是:-
    DisplayPath(strPath)

    VBScript 解析“表达式” (strPath)并通过 结果 DisplayPath .就是这个 结果 这产生了新的存储保存结果的表达式。

    你有没有调用
    DisplayPath strPath

    没有新创建的。

    但是,这又如何:-
    Sub DisplayPath(something)
    MsgBox something
    End Sub

    仍然没有分配新的存储空间。 something将指向与 strPath 相同的内存做。

    编辑

    下面的代码有效:-
    Dim strPath

    strPath = "c:\folder"

    Display


    Sub Display()
    MsgBox strPath
    End Sub

    声明 strPath在过程之外导致它具有全局范围。

    至于使用显式 Dim的意义如果上面的赋值行看起来像这样会发生什么?
     strPath = "c:\folder"

    一个名为 strPath 的新变量将成立和 strPath将保持空白。您应该 总是 用以下行开始您的 VBScript 文件:-
    Option Explicit

    这将迫使您明确 Dim要使用的所有变量,并将为您节省数小时的调试时间。

    关于vbscript - VBScript 函数中的变量范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3835195/

    28 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com