简体   繁体   中英

How to check for “method group” via “sender” object?

Imagine a method like this ( in Win Forms):

//First method
private void buttonStart_Click(object sender, EventArgs e)
{
       //I call another method here
       this.GetData(sender, null)
}

//Second method
private void GetData(object sender, EventArgs e)
{
       //how to check IF calling method is buttonStart_Click ???
       if(sender.Equals == buttonStart_Click) 
       {
            //DO BLAH BLAH
       }
}

I hope I was clear, that is I want to know which method is calling 'GetData'. note I know I can have a global variable and set it to something, but I want to know if there is a DIRECT way to do this?

Thanks.

sender is not going to be buttonStart_Click , it will simply be the button. So you can test for it.

if (sender != null && sender.Equals(buttonStart))
{
   // work with this information
}

However, if you find yourself going down this route, you may end up seeing multiple if blocks each with different behaviors depending on the identity of sender . If that is the case, you'd be better served with a different approach. Have a different handler for each event, encapsulate the differing logic via a delegate, etc. Do not end up with a page full of if / else if / else if / ... .

If you have to do something different because you called the method from some other method, it's probably best to just call a different method:

//First method
private void buttonStart_Click(object sender, EventArgs e)
{
       //I call another method here
       this.SpecialGetData(sender, null)
}

//Second method
private void GetData(object sender, EventArgs e)
{
     // Do regular stuff
}

//Special second method
private void SpecialGetData(object sender, EventArgs e)
{
    //DO BLAH BLAH
}

不知道为什么要这样做,但是如果您需要... http://www.csharp411.com/c-get-calling-method/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM