开发者

Find Class which Call the Method

Hi all There is 2 Classes in project First Class is a form.Like this.

  public partial class Form3 : Form
    {
   开发者_如何学Python     public Form3()
        {
            InitializeComponent();
        }
        private void Form3_Load(object sender, EventArgs e)
        {

        }
    }
}

//And Another Class Like this

public class Sample
{
public void MyMethod()
{
//My Codes
}
}

Now I want to learn that When I call the MyMethod in Form3 or another class I want learn which class called MyMethod? Thanks.


At runtime you can check the method name and the declaring type using following code.

 StackTrace trace=new StackTrace();
            StackFrame[] stackFrames = trace.GetFrames();
            foreach (var stackFrame in stackFrames)
            {
                string methodName= stackFrame.GetMethod().Name;
                string declearingClass=stackFrame.GetMethod().DeclaringType.Name;

            }

you can skip the first frame to know exactly where your function called from

StackFrame[] stackFrames = trace.GetFrames().Skip(1).ToArray();


accept a type object as one of the argument.

public class Sample
{
    public void MyMethod(Type CallerType)
    {
        //My Codes 
    } 
} 

when you are calling that method call

SampleObj.MyMethod(this.gettype());


1) Put a breakpoint in MyMethod()

2) Run your application

3) Wait until that breakpoint hits

4) Look at the stacktrace

Or:

1) Throw and catch an exception in MyMethod

2) Print the exceptions stacktrace


In visual studio, right-click on MyMethod -> Find all references.

Or alternatively, CTRL-K, R with the cursor on the method.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜