Caller on. NET

Source: Internet
Author: User
The easiest,

Public class CallerTest {

Static
Public void Main (string [] args ){

Try {

Level1 ();

} Catch (Exception ex)
{

Console. WriteLine (ex );

}
Finally {

Console. ReadLine ();

}

}

 

Static
Void level1 ()
{

Level2 ();

}

 

Static
Void level2 ()
{

Stacktrace ST = new stacktrace ();

If (St. framecount
> 1 ){

Stackframe stframe =
St. getframe (1 );

Console. WriteLine (stFrame. GetMethod ());

}

}

}

 

If you enable the fNeedFileInfo switch, new StackTrace (true), you can trace the corresponding file name and row number.

 

Then we can observe from the object perspective,

Public class CallerTest {

Class
Callee {

Public void callAtCallee (){

StackTrace st = new StackTrace (1, true );

Console. WriteLine ("{0}. {1}", st. GetFrame (0). GetMethod (). ReflectedType. Name,
St. GetFrame (0). GetMethod (). Name );

}

}

 

Class
Caller {

Public void callAtCaller (Callee ee ){

Ee. callAtCallee ();

}

}

 

Static
Public void Main (string [] args ){

Try {

New Caller (). callAtCaller (new Callee ());

} Catch (Exception ex)
{

Console. WriteLine (ex );

} Finally {

Console. ReadLine ();

}

}

}

 

St. getframe (0 ). getmethod (). reflectedtype. name refers to the class where the corresponding methodbase is located, and St. getframe (0 ). getmethod (). name indicates the method name.

In this way, we can easily obtain the call class and method signature in the callatcallee method.

 

It seems difficult to obtain the specific object to call...

If you know, leave me a method. Thank you.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.