如何检查“方法组”通过“发送者”目的?
想象一下这样的方法(在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
}
}
我希望我很清楚,那就是我想知道哪个方法正在调用“GetData”。 注意 我知道我可以拥有一个全局变量并将其设置为某个值,但我想知道是否有直接的方法可以做到这一点?
谢谢。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
sender
不会是buttonStart_Click
,它只是按钮。所以你可以测试一下。但是,如果您发现自己沿着这条路线走下去,您最终可能会看到多个
if
块,每个块具有不同的行为,具体取决于发送者
的身份。如果是这种情况,您最好采用不同的方法。为每个事件使用不同的处理程序,通过委托封装不同的逻辑等。不要以充满if / else if / else if / ... 的页面结束。
sender
is not going to bebuttonStart_Click
, it will simply be the button. So you can test for it.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 ofsender
. 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 ofif / 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:
不知道你为什么这样做,但如果你需要......
http://www.csharp411.com/c-get-calling-method/
Not sure why you do this way, but if you need...
http://www.csharp411.com/c-get-calling-method/