Obtener el nombre del método actual
Esta es una pregunta tonta, pero ¿es posible obtener el nombre del método que se está ejecutando actualmente desde ese método?
Public Sub SomeMethod()
Dim methodName as String = System.Reflection.[function to get the current method name here?]
End Sub
Gracias
5 answers
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-01-07 15:26:30
Los otros métodos están cerca de lo que se preguntó, pero no devuelven el valor string. Pero esto sí:
Dim methodName$ = System.Reflection.MethodBase.GetCurrentMethod().Name
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-01-29 22:42:32
Para garantizar que cualquiera de las respuestas presentadas a esta pregunta realmente funcione (System.Reflection.MethodBase.GetCurrentMethod().Name
) en tiempo de ejecución, debe agregar un atributo. No hay ningún indicador de compilador/tiempo de ejecución que sepa que rompa este método:
La función que está tratando de obtener el nombre de debe estar marcada
- 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)]
También, hoy en día, existe la nameof()
operador en VB, C#( y tal vez F# pronto)
que para su caso sería nameof(SomeMethod)
(Creo que la sintaxis sería la misma para VB y C# aquí)
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 10:31:02
Otro enfoque sería usar CallerMemberNameAttribute desde el Sistema.Ejecución.CompilerServices espacio de nombres para rellenar un parámetro opcional. Por ejemplo ...
Private Function GetMethodName(<System.Runtime.CompilerServices.CallerMemberName>
Optional memberName As String = Nothing) As String
Return memberName
End Function
La función sería invocada como es de esperar...
Public Sub DoSomeWork()
Dim methodName As String = GetMethodName()
Console.WriteLine($"Entered {methodName}")
' Do some work
End Sub
En lugar de 'solo' recuperar el nombre del método, la función también podría hacer uso del nombre del método recuperado para simplificar aún más el código. Por ejemplo...
Private Sub TraceEnter(
<System.Runtime.CompilerServices.CallerMemberName>
Optional memberName As String = Nothing)
Console.WriteLine($"Entered {memberName}")
End Sub
... que podría ser utilizado de esta manera ...
Public Sub DoSomeWork()
TraceEnter()
' Do some work
End Sub
Otros atributos en el espacio de nombres CompilerServices se pueden usar de manera similar para recuperar la ruta completa (en tiempo de compilación) del archivo fuente y/o el número de línea de la llamada. Consulte la documentación de CallerMemberNameAttribute para ver el código de ejemplo.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-06-04 06:33:36
Dim methodName As String = System.Reflection.MethodBase.GetCurrentMethod().Name
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-12-07 19:37:35