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:
xxxxxxxxxx
1
string methodName = nameof(this.SomeMethodHere); // C# 6 or later
2
3
// or
4
5
MethodBase method = MethodBase.GetCurrentMethod(); // call it inside your method
6
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.
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.
xxxxxxxxxx
1
using System;
2
3
public static class Program
4
{
5
private static void DoMethod()
6
{
7
string name = nameof(DoMethod);
8
9
Console.WriteLine("Currently called method name is " + name);
10
}
11
12
public static void Main(string[] args)
13
{
14
DoMethod();
15
}
16
}
Resultado:
xxxxxxxxxx
1
Currently called method name is DoMethod.
Esta solução foi introduzida na versão anterior do .NET - pode ser usada sem se preocupar se é suportada.
xxxxxxxxxx
1
using System;
2
using System.Diagnostics;
3
using System.Reflection;
4
5
public static class Program
6
{
7
private static void DoMethod()
8
{
9
MethodBase method = MethodBase.GetCurrentMethod();
10
11
Console.WriteLine("Currently called method name is " + method.Name);
12
}
13
14
public static void Main(string[] args)
15
{
16
DoMethod();
17
}
18
}
Resultado:
xxxxxxxxxx
1
Currently called method name is DoMethod.
É uma maneira alternativa adicional para exemplos anteriores.
xxxxxxxxxx
1
using System;
2
using System.Diagnostics;
3
using System.Reflection;
4
5
public static class Program
6
{
7
private static void DoMethod()
8
{
9
StackTrace trace = new StackTrace();
10
11
StackFrame frame = trace.GetFrame(0);
12
MethodBase method = frame.GetMethod();
13
14
Console.WriteLine("Currently called method name is " + method.Name + ".");
15
}
16
17
public static void Main(string[] args)
18
{
19
DoMethod();
20
}
21
}
Resultado:
xxxxxxxxxx
1
Currently called method name is DoMethod.