2008-11-11 8 views
5

"How can I find the method that called the current method?"발신자 기능은 어떻게 찾습니까?

의 정확한 중복으로 휴일은 C#을 가진 수 this인가?

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? –

+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-the-current-method) –

답변

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

그러나이 견고하지 특히로서 (예컨대 인라인 JIT)을 최적화인지 스택 프레임 수 원숭이.

+0

안녕하세요, Marc. JIT 때문에 런타임 중에 메서드 이름이 바뀔 수 있습니까? – Joe

+0

@Joe 인라이닝 (inlining) 때문이거나 익명 메소드 및 반복자 블록과 같은 컴파일러에서 생성 된 메소드로 인해 * 예상 한 *을 얻지 못할 수도 있습니다. 난 당신이 obfuscator를 사용하지 않는다면, 갑자기 완전히 이름이 바뀌 길 기대하지 않을 것입니다. –

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); 

을하지만이 멀티 스레딩 작동하지 않을 수 있다는 발언도있다.

+1

발언에 대해 많은 감사드립니다. 내가 새 스레드 내부에서 메서드 이름을 가져 오려고했을 때 왜 'NullReferenceException'을 얻었는지 궁금합니다. – Animesh

관련 문제