是否可以在VB.NET中获取引用方法?

And*_*ers 8 vb.net

看这个例子:

''//file1.vb
Sub Something()
    ''//...
    Functions.LogInfo("some text")
    ''//...
End Sub

''//functions.vb
Sub LogInfo(ByVal entry as String)

    Console.WriteLine(entry)

End Sub
Run Code Online (Sandbox Code Playgroud)

我可以在LogInfo中获得名称"Something"吗?

对于这篇文章的简要说明,我不知道如何恰当地表达这个问题.我会根据需要澄清和阐述.

Jon*_*eet 12

(编辑:删除了不必要的使用StackTrace本身 - 如果你想要打印的信息不仅仅是一帧,这将非常有用.)

您可以使用StackFrame该类,但它相当昂贵(IIRC)并且可能由于内联而略微不正确.

编辑:这样的事情:( NoInlining是为了确保它的行为正常......)

Imports System.Diagnostics
Imports System.Runtime.CompilerServices

Public Class Test

    Shared Sub Main()
        Something()
    End Sub        

    <MethodImpl(MethodImplOptions.NoInlining)> _
    Shared Sub Something()        
        Functions.LogInfo("some text")
    End Sub

End Class

Public Class Functions

    <MethodImpl(MethodImplOptions.NoInlining)> _
    Public Shared Sub LogInfo (ByVal entry as String)
        Dim frame as StackFrame = new StackFrame(1, False)
        Console.WriteLine("{0}: {1}", _
                          frame.GetMethod.Name, _
                          entry)
    End Sub

End Class
Run Code Online (Sandbox Code Playgroud)


Qui*_*son 6

看看如何找到调用当前方法的方法?.

转换为VB(希望):

Imports System.Diagnostics
''// get call stack
Dim stackTrace As New StackTrace()

''// get calling method name
Console.WriteLine(stackTrace.GetFrame(1).GetMethod().Name)
Run Code Online (Sandbox Code Playgroud)