PT
C# / .NET - obter o atual método nome
3
points
Neste artigo, veremos como obter o atual método nome em C# / .NET.
Solução rápida:
string methodName = nameof(this.SomeMethodHere); // C# 6 or later
// or
MethodBase method = MethodBase.GetCurrentMethod(); // call it inside your method
string methodName = method.Name;
Existem duas abordagens sobre como fazê-lo:
- com built-in nameof operator - introduzido em C# 6,
- com a API de Reflexão.
1. Exemplo de nameof
operator
Essa abordagem não usa diretamente instruções, namespaces de reflexão e classes.
Nota: o operador
nameof
está disponível no C # 6 e posterior.
using System;
public static class Program
{
private static void DoMethod()
{
string name = nameof(DoMethod);
Console.WriteLine("Currently called method name is " + name);
}
public static void Main(string[] args)
{
DoMethod();
}
}
Resultado:
Currently called method name is DoMethod.
2. Exemplo do método MethodBase.GetCurrentMethod
Esta solução foi introduzida na versão anterior do .NET - pode ser usada sem se preocupar se é suportada.
using System;
using System.Diagnostics;
using System.Reflection;
public static class Program
{
private static void DoMethod()
{
MethodBase method = MethodBase.GetCurrentMethod();
Console.WriteLine("Currently called method name is " + method.Name);
}
public static void Main(string[] args)
{
DoMethod();
}
}
Resultado:
Currently called method name is DoMethod.
3. Exemplo de classe StackTrace
É uma maneira alternativa adicional para exemplos anteriores.
using System;
using System.Diagnostics;
using System.Reflection;
public static class Program
{
private static void DoMethod()
{
StackTrace trace = new StackTrace();
StackFrame frame = trace.GetFrame(0);
MethodBase method = frame.GetMethod();
Console.WriteLine("Currently called method name is " + method.Name + ".");
}
public static void Main(string[] args)
{
DoMethod();
}
}
Resultado:
Currently called method name is DoMethod.