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();
Edw*_*ard 38
其他方法与所询问的方法很接近,但它们不返回字符串值.但这样做:
Dim methodName$ = System.Reflection.MethodBase.GetCurrentMethod().Name
Run Code Online (Sandbox Code Playgroud)
为确保针对此问题的任何答案System.Reflection.MethodBase.GetCurrentMethod().Name在运行时()都能正常工作,您需要添加一个属性。据我所知,没有编译器/运行时标志会破坏此方法:
您要获取名称的函数必须标记
[<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#语法是相同的)
另一种方法是使用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 文档。
| 归档时间: |
|
| 查看次数: |
47767 次 |
| 最近记录: |