2008-11-11 4 views
5

закрыт, как точная копия "How can I find the method that called the current method?"Как вы находите функцию звонящего?

ли this возможно с C#?

void main() 
{ 
    Hello(); 
} 

void Hello() 
{ 
    // how do you find out the caller is function 'main'? 
} 
+0

http://stackoverflow.com/questions/171970/how-can-i-find-the-method-that-called-the-current-method? – 2008-11-11 09:30:01

+0

Этот вопрос является дубликатом [http://stackoverflow.com/questions/171970/how-can-i-find-the-method-that-called-the-current-method](http://stackoverflow.com/questions/171970/how-can-i-find-the-method-that-called-the-current-method) – 2008-11-11 09:30:59

ответ

17
Console.WriteLine(new StackFrame(1).GetMethod().Name); 

Тем не менее, это не надежный, особенно в оптимизаций (например, JIT встраивание) может обезьяна с воспринимаемыми кадров стека.

+0

Привет, Марк. Было бы возможно, из-за JIT, что имя метода может измениться во время выполнения? – Joe 2012-03-14 13:50:08

3

here От:

System.Diagnostics.StackTrace st = new System.Diagnostics.StackTrace(1); 
System.Diagnostics.StackFrame sf = st.GetFrame(0); 
string msg = sf.GetMethod().DeclaringType.FullName + "." + 
sf.GetMethod().Name; 
MessageBox.Show(msg); 

Но есть замечание, что это не может работать с несколькими потоками.