Get the name of the current method

2020-05-29 12:28发布

This is kind of a silly question, but is it possible to get the name of the method that is currently being executed from within that method?

Public Sub SomeMethod()

   Dim methodName as String = System.Reflection.[function to get the current method name here?]

End Sub

Thanks

5条回答
爷、活的狠高调
2楼-- · 2020-05-29 13:04

The other methods are close to what was asked, but they don't return the string value. But this does:

Dim methodName$ = System.Reflection.MethodBase.GetCurrentMethod().Name
查看更多
欢心
4楼-- · 2020-05-29 13:05

To guarantee that any of the answers presented to this question actually work (System.Reflection.MethodBase.GetCurrentMethod().Name) at runtime, you need to add an attribute. There are no compiler/runtime flags that I know of that break this method:

the function you are trying to get the name of must be marked

  • F# [<System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)>]
  • VB: <System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)>

  • C#: [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]

Also, nowadays, there is the nameof() operator in VB, C#(and maybe F# soon) which for your case would be nameof(SomeMethod) (I believe the syntax would be the same for VB and C# here)

查看更多
We Are One
5楼-- · 2020-05-29 13:12
Dim methodName As String = System.Reflection.MethodBase.GetCurrentMethod().Name
查看更多
Animai°情兽
6楼-- · 2020-05-29 13:17

Another approach would be to use Caller​Member​Name​Attribute from the System.​Runtime.​Compiler​Services namespace to populate an optional parameter. For example ...

Private Function GetMethodName(<System.Runtime.CompilerServices.CallerMemberName>
    Optional memberName As String = Nothing) As String

    Return memberName

End Function

The function would be invoked as you would expect...

Public Sub DoSomeWork()
    Dim methodName As String = GetMethodName()
    Console.WriteLine($"Entered {methodName}")

    ' Do some work
End Sub

Rather than 'just' retrieving the method name, the function might also make use of the method name retrieved to further simplify code. For example...

Private Sub TraceEnter(
    <System.Runtime.CompilerServices.CallerMemberName>
    Optional memberName As String = Nothing)

    Console.WriteLine($"Entered {memberName}")

End Sub

... which might be used like this ...

Public Sub DoSomeWork()
    TraceEnter()

    ' Do some work

End Sub

Other attributes in the CompilerServices namespace may be used in similar fashion to retrieve the full path (at compile time) of the source file and/or the line number of the call. See the CallerMemberNameAttribute documentation for sample code.

查看更多
登录 后发表回答