2009-07-22 7 views
3

Possible en double:
How can I find the method that called the current method?C# Méthode appelant

Salut, comment puis-je déterminer l'appelant d'une méthode à partir de la méthode? Par exemple:

SomeNamespace.SomeClass.SomeMethod() { 
    OtherClass(); 
} 

OtherClass() { 
    // Here I would like to able to know that the caller is SomeNamespace.SomeClass.SomeMethod 
} 

Merci

+4

Dupe - http://stackoverflow.com/ questions/171970/comment-je-trouve-la-méthode-que-dite-la-méthode-courante et http://stackoverflow.com/questions/280413/c-how-do-you-find-the- caller-function-closed – William

Répondre

6

Ces articles doivent être utiles:

  1. http://iridescence.no/post/GettingtheCurrentStackTrace.aspx
  2. http://blogs.msdn.com/jmstall/archive/2005/03/20/399287.aspx

Fondamentalement, le code ressemble à ceci:

StackFrame frame = new StackFrame(1); 
MethodBase method = frame.GetMethod(); 
message = String.Format("{0}.{1} : {2}", 
method.DeclaringType.FullName, method.Name, message); 
Console.WriteLine(message); 
+5

Faites attention. J'ai été attrapé par ce bug une fois. Si vous créez votre application pour publication, la méthode peut être alignée et votre trace de pile sera différente. – Anish

1

Vous devez utiliser la classe StackTrace

Snippet du MSDN

// skip the current frame, load source information if available 
StackTrace st = new StackTrace(new StackFrame(1, true)) 
Console.WriteLine(" Stack trace built with next level frame: {0}", 
    st.ToString()); 
1

Vous pouvez utiliser la classe System.Diagnostics.StackTrace:

StackTrace stackTrace = new StackTrace();   // get call stack 
    StackFrame[] stackFrames = stackTrace.GetFrames(); // get method calls (frames) 

    // write call stack method names 
    foreach (StackFrame stackFrame in stackFrames) 
    { 
    Console.WriteLine(stackFrame.GetMethod().Name); // write method name 
    } 
Questions connexes