Languages
[Edit]
PT

C# / .NET - obter o atual método nome

3 points
Created by:
Alyona
1140

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.

Referências:

  1. StackTrace Class - Microsoft docs
  2. StackFrame.GetMethod Method - Microsoft docs
  3. nameof operator - Microsoft Docs
Native Advertising
­čÜÇ
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - friendly IT community for everyone.

ÔŁĄ´ŞĆ­čĺ╗ ­čÖé

Join