[英]How do I pass extra arguments to my event handlers?
I am trying to call a shared global event handler from my form's button click event. 我试图从表单的按钮单击事件中调用共享的全局事件处理程序。
public void button21_Click(object me, EventArgs MyArgs) {
button17_Click(me, MyArgs); /// WORKS!
}
What I want to do is pass in my XML to the method. 我要做的是将XML传递给该方法。
Something like: 就像是:
public void button21_Click(object me, EventArgs MyArgs) {
button17_Click(me, MyArgs, MyXmlString); /// ERROR!
}
I do not always need XML in the button17_Click() method, only when button21 is pressed. 仅在按下button21时,我并不总是在button17_Click()方法中需要XML。
How can I do this? 我怎样才能做到这一点?
You don't pass XML (or other arbitrary data types) to event handlers in .NET. 您不会将XML(或其他任意数据类型)传递给.NET中的事件处理程序。 They have a particular signature, and that's what you have to use.
它们具有特定的签名,这就是您必须使用的签名。
You should not be calling button17_click from button21_click. 您不应该从button21_click调用button17_click。 Instead, try this:
相反,请尝试以下操作:
public void button17_Click(object sender, EventArgs e)
{
CommonFunctionality();
}
public void button21_Click(object sender, EventArgs e)
{
CommonFunctionality();
}
private void CommonFunctionality()
{
// In here, place the code that used to be in button17_click
}
You may then need to create a version of the common functionality that can use your XML. 然后,您可能需要创建可以使用XML的通用功能的版本。
I would not try to call your event handler directly, leave that up to the events themselves. 我不会尝试直接调用您的事件处理程序,而是让事件自己处理。
What you should do instead is move the logic for button17
into a separate method and call that method instead. 相反,您应该做的是将
button17
的逻辑button17
单独的方法中,然后调用该方法。
private void button17_Click(object sender, EventArgs e)
{
// call the newly created method instead (with the XML argument null)
HandleClickOperation(null);
}
private void button21_Click(object sender, EventArgs e)
{
// call the newly created method instead (with the XML argument set)
HandleClickOperation(MyXmlString);
}
private void HandleClickOperation(string xmlString)
{
if (xmlString == null)
{
// do things unique to button17 behavior
}
else
{
// do things unique to button21 behavior
}
// the logic that was in button17_Click()
}
OK, this question is a little better than yesterday, bu we still can't see : 好,这个问题比昨天好一点,但是我们仍然看不到:
And all that is needed to form an answer or an advice. 以及形成答案或建议所需的一切。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.