PL
C# / .NET - pobieranie aktualnej nazwy metody / funkcji
3 points
W tym artykule przyjrzymy się, jak uzyskać aktualną nazwę metody w C# / .NET.
Szybkie rozwiązanie:
xxxxxxxxxx
1
string methodName = nameof(this.SomeMethodHere); // C# 6 lub nowsze
2
3
// lub
4
5
MethodBase method = MethodBase.GetCurrentMethod(); // wywołaj poniższy kod w docelowej funkcji
6
string methodName = method.Name;
Można to wykonać używając:
- wbudowanego operatora
nameof
- wprowadzony dopiero w C# 6, - mechanizmu refleksji (Reflection API).
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#.
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
}
Wynik:
xxxxxxxxxx
1
Currently called method name is DoMethod.
To rozwiązanie zostało wprowadzone we wcześniejszej wersji .NET - można z niego korzystać bez obaw, braku wsparcia.
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
}
Wynik:
xxxxxxxxxx
1
Currently called method name is DoMethod.
To jest dodatkowy, alternatywny sposób dla poprzednich przykładów.
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
}
Wynik:
xxxxxxxxxx
1
Currently called method name is DoMethod.