Languages
[Edit]
PL

C# / .NET - pobieranie aktualnej nazwy metody / funkcji

3 points
Created by:
Sylwia
3590

W tym artykule przyjrzymy się, jak uzyskać aktualną nazwę metody w C# / .NET.

Szybkie rozwiązanie:

string methodName = nameof(this.SomeMethodHere);   //  C# 6 lub nowsze

// lub

MethodBase method = MethodBase.GetCurrentMethod(); //  wywołaj poniższy kod w docelowej funkcji
string methodName = method.Name;

Można to wykonać używając:

  • wbudowanego operatora nameof - wprowadzony dopiero w C# 6,
  • mechanizmu refleksji (Reflection API).

 1. Operator nameof przykład:

Używając tego podejścia nie jest wymagane załączenie dodatownych przestrzeni nazw - wystarczy operator.

Uwaga: operator nameof jest dostępny w języku C# 6 i nowszych wersjach, więc należy upewnić się czy nasz projekt został skonfigurowany poprawnie i czy mamy zainswtalowaną odpowiednią wersję języka C#.

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();
	}
}

 Wynik:

Currently called method name is DoMethod.

2. Przykład metody MethodBase.GetCurrentMethod

To rozwiązanie zostało wprowadzone we wcześniejszej wersji .NET - można z niego korzystać bez obaw, braku wsparcia.

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();
	}
}

Wynik:

Currently called method name is DoMethod.

3. Przykład klasy StackTrace

To jest dodatkowy, alternatywny sposób dla poprzednich przykładów.

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();
	}
}

Wynik:

Currently called method name is DoMethod.

Bibliografia

  1. StackTrace Class - Microsoft docs
  2. StackFrame.GetMethod Method - Microsoft docs
  3. nameof operator - Microsoft Docs
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join