1

VBScript 中是否可以确定当前正在执行的函数的名称?

在 .NET 中,您可以执行以下操作:

MethodBase method = MethodBase.GetCurrentMethod();
Console.WriteLine(method.Name);
4

2 回答 2

3

过去,我构建了一个调用堆栈查看器来查看每个被调用函数的性能。这需要每个函数/子额外的一行 VBS 代码,当然,由于额外的代码,在运行时需要一些开销。

自下而上:

Function DoSomething(a, b, c)
    dim registerFunctionObj : Set registerFunctionObj = [new RegisterFunction]("DoSomething")

    ' other code
End Function

每当调用该函数时,它都会创建一个 RegisterFunction 对象的新实例。当函数退出时,registerFunctionObj变量自动超出范围,调用实例的 Class_Terminate 子。

[new RegisterFunction]只是一个返回 registerFunction 实例的函数:

Function [new RegisterFunction](funcName)
    Set [new RegisterFunction] = new cls_RegisterFunction
    [new RegisterFunction].FunctionName = funcName
    Set [new RegisterFunction].CallStackViewer = CallStackViewer
End function

Class cls_RegisterFunction

    Private functionName_, startTime_, callStackViewer_, endTime_
    Private Sub Class_Initialize
        startTime_ = now
        callStackViewer_.LogInitialize me
    End Sub

    Public Property Let FunctionName(fName)
        functionName_ = fName
    End Property

    Public Property Set CallStackViewer(byRef csv)
        Set callStackViewer_ = csv
    End Property

    Private Sub Class_Terminate
        endTime_ = now
        callStackViewer_.LogTerminate me
    End Sub

End Class

CallStackViewer 实例是 CallStackViewer 类的单例实例,但您可以将其作为项目的一部分,因此您可以通过全局项目类检索它:

Private PRIV_callStackViewer
Public Function CallStackViewer()
    If not IsObject(PRIV_callStackViewer) Then
        Set PRIV_callStackViewer = new cls_CallStackViewer
    End If
    Set CallStackViewer = PRIV_callStackViewer
End Function

Class cls_CallStackViewer
    Public Sub Class_Initialize
        ' Here you can retrieve all function libraries (as text file) extract the 
        ' function name, the file they are in and the linenumber
        ' Put them in a dictionary or a custom object
    End Sub

    Public Sub LogInitialize(byref registerFunction)
        ' Here you can push the function on a stack (use a standard dotnet list>stack for it),
        ' log the starttime to a log object or handle custom breakpoints
    End Sub

    Public Sub LogTerminate(byref registerFunction)
        ' Here you can pop the function from a stack, log the endtime to a log
        ' object or handle custom breakpoints
    End Sub

End Class

免责声明:此处的代码是动态创建的纯演示代码。它缺乏功能,只是在这里解释这个概念。它可能包含错误并且不完整。

您唯一需要的是每个函数的一行代码和您自己的想象力来扩展它。

于 2012-04-20T13:22:22.850 回答
0

不,但您可以轻松实现它

dim module_name

sub sub1
  module_name = "sub1"
  wscript.echo "i'm " & module_name
  'do something
end sub

function function1
  module_name = "function1"
  wscript.echo "i'm " & module_name
  function1 = "something"
end function

在递归的情况下,您还可以记住您所处的级别,以便在太深时可以退出。

于 2012-04-19T23:05:17.493 回答