Rispondere “Quale metodo mi ha chiamato?” Al runtime in .NET? O è dati CallStack leggibile dal codice?

StackOverflow https://stackoverflow.com/questions/1873998

Domanda

presumere che ci sono Methoda (), MethodB () e methodC ().

E methodC () viene chiamato in fase di esecuzione.

È è possibile conoscere methodC () viene chiamato dal quale metodo?

Stavo pensando se CallStack può essere letta al runtime per alcuni controlli? Se sì, penso che non dovrebbe essere un grosso problema.

Tutte le idee?

Grazie!

È stato utile?

Soluzione

Utilizzare le classi StackTrace e StackFrame. Ad esempio:

  StackTrace stackTrace = new StackTrace();          
  StackFrame[] stackFrames = stackTrace.GetFrames();

  foreach (StackFrame stackFrame in stackFrames)
  {
    string method = stackFrame.GetMethod().Name;
    // do some stuff with method
  }

Altri suggerimenti

Sì, lo stack di chiamate può essere letta in fase di esecuzione utilizzando StackTrace.GetFrames .

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top