C# 如何在中为事件返回值(气泡值向上)?
我正在尝试更改事件参数中的值。不确定这是否可行,但这是父类中的当前事件:C# 如何在中为事件返回值(气泡值向上)?,c#,.net,asp.net,events,event-handling,C#,.net,Asp.net,Events,Event Handling,我正在尝试更改事件参数中的值。不确定这是否可行,但这是父类中的当前事件: public void MasterClass() { void btnSubmit_Click(object sender, EventArgs e) { ... OnInputBound(this, new InputEventArgs(postName, value)); //I would like to try something like this but does
public void MasterClass()
{
void btnSubmit_Click(object sender, EventArgs e)
{
...
OnInputBound(this, new InputEventArgs(postName, value));
//I would like to try something like this but does not work:
//value = OnInputBound(this, new InputEventArgs(postName, value));
//Continue with new value...
}
}
在应用程序的其他部分中,它们通常按如下方式注册事件:
protected override void CreateChildControls()
{
MyForm.OnInputBound += new EventHandler<InputEventArgs>(MyForm_OnInputBound);
}
void MyForm_OnInputBound(object sender, SingleForm.InputEventArgs e)
{
e.Value = "new value";
}
protectedoverride void CreateChildControls()受保护的覆盖
{
MyForm.OnInputBound+=新事件处理程序(MyForm_OnInputBound);
}
void MyForm_onInputBounded(对象发送方,SingleForm.InputEventArgs e)
{
e、 Value=“新值”;
}
注意我是如何试图改变MasterClass的论点的。这显然不起作用,但如何将该值冒泡起来?您需要保留对
InputEventArgs
实例的引用,以便在引发事件后从中读取值:
void btnSubmit_Click(object sender, EventArgs e)
{
...
InputEventArgs eventArgs = new InputEventArgs(postName, value);
OnInputBound(this, eventArgs);
value = eventArgs.Value;
//Continue with new value...
}
这里需要注意的一点是,存在可能导致意外结果的场景:
- 侦听器可以选择生成线程并异步处理调用
- 同一事件可能有多个侦听器,每个侦听器都可以指定不同的值。当然,您的代码将只看到最后分配的一个,但是您将无法控制侦听器的调用顺序
以以下情况为例(上文第一点):
在这种情况下,不能保证在btnsupmit\u中的代码单击从InputEventArgs
实例中拾取“新”值之前分配该值
void MyForm_OnInputBound(object sender, SingleForm.InputEventArgs e)
{
ThreadPool.QueueUserWorkItem(state =>
{
// perform some potentially lengthy database lookup or such
// and then assign a new value
e.Value = "new value";
});
}