获取当前方法的名称

cam*_*inc 62 .net vb.net reflection

这是一个愚蠢的问题,但是有可能从该方法中获取当前正在执行的方法的名称吗?

Public Sub SomeMethod()

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

End Sub
Run Code Online (Sandbox Code Playgroud)

谢谢

her*_*ter 122

System.Reflection.MethodInfo.GetCurrentMethod();

  • 更好地使用基类:System.Reflection.MethodBase.GetCurrentMethod(); (11认同)
  • @PunkyGuy有人说:"尽管两个调用具有完全相同的效果,但在实际定义它们的类的子类上调用共享函数通常是个坏主意".参考文献:http://bytes.com/topic/visual-basic-net/answers/457334-methodinfo-methodbase (5认同)
  • @marstone - 你能解释一下为什么吗? (2认同)

Edw*_*ard 38

其他方法与所询问的方法很接近,但它们不返回字符串值.但这样做:

Dim methodName$ = System.Reflection.MethodBase.GetCurrentMethod().Name
Run Code Online (Sandbox Code Playgroud)


Mas*_*low 5

为确保针对此问题的任何答案System.Reflection.MethodBase.GetCurrentMethod().Name在运行时()都能正常工作,您需要添加一个属性。据我所知,没有编译器/运行时标志会破坏此方法:

您要获取名称的函数必须标记

  • 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)]

另外,如今,nameof()VB中有运算符,C#(可能不久后还有F#),对于您而言,这是运算符nameof(SomeMethod)(我相信这里的VB和C#语法是相同的)


Fra*_*yne 5

另一种方法是使用System.?Runtime.?Compiler?Services 命名空间中的Caller?Member?Name?Attribute来填充可选参数。例如 ...

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

    Return memberName

End Function
Run Code Online (Sandbox Code Playgroud)

该函数将按照您的预期被调用......

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

    ' Do some work
End Sub
Run Code Online (Sandbox Code Playgroud)

与“仅仅”检索方法名称不同,该函数还可以利用检索到的方法名称来进一步简化代码。例如...

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

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

End Sub
Run Code Online (Sandbox Code Playgroud)

......可能像这样使用......

Public Sub DoSomeWork()
    TraceEnter()

    ' Do some work

End Sub
Run Code Online (Sandbox Code Playgroud)

CompilerServices 命名空间中的其他属性可以类似方式用于检索源文件的完整路径(在编译时)和/或调用的行号。有关示例代码,请参阅 CallerMemberNameAttribute 文档。