获取当前方法的名称
更好地使用基类: System.Reflection.MethodBase。GetCurrentMethod(); – marstone 2014-01-06 07:34:32
@marstone - 你能解释一下为什么这么好吗? – PunkyGuy 2014-06-23 14:32:01
@PunkyGuy有人说:“虽然这两个调用具有完全相同的效果,但在实际定义的类的子类上调用共享函数通常是一个坏主意。参考:http://bytes.com/topic/visual-basic-net/answers/457334-methodinfo-methodbase – marstone 2014-06-24 12:02:14
其他方法都接近了什么要求,但他们不返回字符串值。但这:
Dim methodName$ = System.Reflection.MethodBase.GetCurrentMethod().Name
宾果!为我解决 – 2018-02-01 18:59:02
Dim methodName As String = System.Reflection.MethodBase.GetCurrentMethod().Name
要保证任何提出这个问题的答案,实际上在运行时正常工作(System.Reflection.MethodBase.GetCurrentMethod().Name
),你需要添加一个属性。有没有编译器/运行的标志,我知道,突破此方法:
功能你试图让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)]
此外,时下,有在VB中nameof()
操作,C#(and maybe F# soon) 这对于你的情况是nameof(SomeMethod)
(我相信语法将是VB和C#这里是相同的)
另一种方法是使用CallerMemberNameAttribute来自System。Runtime。Compiler Services命名空间来填充可选参数。例如...
Private Function GetMethodName(<System.Runtime.CompilerServices.CallerMemberName>
Optional memberName As String = Nothing) As String
Return memberName
End Function
的功能将被调用你所期望的......
Public Sub DoSomeWork()
Dim methodName As String = GetMethodName()
Console.WriteLine($"Entered {methodName}")
' Do some work
End Sub
而不是“只是”检索方法的名称,功能也可能利用方法检索名称以进一步简化代码。例如...
Private Sub TraceEnter(
<System.Runtime.CompilerServices.CallerMemberName>
Optional memberName As String = Nothing)
Console.WriteLine($"Entered {memberName}")
End Sub
...这可能是这样使用...
Public Sub DoSomeWork()
TraceEnter()
' Do some work
End Sub
在CompilerServices命名空间中的其他属性可以以类似的方式被用于检索的完整路径(在编译时间)的源文件和/或呼叫的线路号码。有关示例代码,请参阅CallerMemberNameAttribute文档。
看看这个:http://geekswithblogs.net/opiesblog/archive/2006/06/29/83654.aspx – 2010-01-12 18:11:57
这实际上是如何获得调用方法的名称,而不是当前正在执行的方法。尽管如此,仍然很酷! – 2010-01-12 18:21:24
[可以使用反射来查找当前正在执行的方法的名称?](http://*.com/questions/44153/can-you-use-reflection-to-find-the-name-of当前执行方法) – 2017-01-25 22:52:36