VBScript确定正在运行的函数

时间:2012-04-19 21:12:10

标签: vbscript

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

在.NET中,您可以这样做:

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

2 个答案:

答案 0 :(得分:3)

过去,我构建了一个callstack查看器来查看所调用的每个函数的性能。由于额外的代码,每个函数/ sub需要额外的一行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

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

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

答案 1 :(得分: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

如果是递归,你也可以记住你的水平,这样你就可以走得太远。

相关问题