2012-04-12 5 views
44

Eventuali duplicati:
Can you use reflection to find the name of the currently executing method?
C# how to get the name of the current method from codeCome ottenere il nome della funzione corrente?

Ad esempio:

void foo() { 
    Console.Write(__MYNAME__); 
} 

stampa: foo

i è possibile farlo in C#?

+0

In .Net 4.5, è possibile utilizzare CallerMemberNameAttribute per ottenere il nome del chiamante. Vedi https://msdn.microsoft.com/en-us/library/system.runtime.compilerservices.callermembernameattribute(v=vs.110).aspx ... Puoi quindi avvolgere il corpo della tua funzione in una funzione anonima come in ([CallerMemberName] string functionName = "") => {}. I problemi con l'uso del metodo di riflessione come nella risposta accettata sono che (1) la funzione può essere inline, e/o (2) il nome della funzione può essere offuscato se non è pubblico e il codice è offuscato. – GreatAndPowerfulOz

risposta

102

Prova questa:

System.Reflection.MethodBase.GetCurrentMethod().Name 
+3

Esattamente. Grazie – Jack

+5

Per le persone che utilizzano .Net 4.5, c'è [CallerMemberNameAttribute] (https://msdn.microsoft.com/en-us/library/system.runtime.compilerservices.callermembernameattribute.aspx) –

14

È possibile controllare l'analisi dello stack

using System.Diagnostics; 

// get call stack 
StackTrace stackTrace = new StackTrace(); 

// get calling method name 
Console.WriteLine(stackTrace.GetFrame(0).GetMethod().Name); 

Ma attenzione, se il metodo è inline si ottiene il nome del metodo genitore.