【发布时间】:2011-02-10 04:12:41
【问题描述】:
我在处理事件被提升为封闭形式并希望获得一些帮助的情况时遇到了问题。
场景(参考以下代码):
-
Form1打开Form2 -
Form1订阅了Form2上的一个事件(我们称这个事件为FormAction) -
Form1已关闭,Form2保持打开状态 -
Form2引发FormAction事件
在Form1.form2_FormAction 中,为什么this 返回对Form1 的引用而button1.Parent 返回null?他们不应该都返回相同的引用吗?
如果我们省略第 3 步,this 和 button1.Parent 都会返回相同的引用。
这是我正在使用的代码...
Form1:
public partial class Form1 : Form
{
public Form1 ()
{
InitializeComponent();
}
private void button1_Click ( object sender , EventArgs e )
{
// Create instance of Form2 and subscribe to the FormAction event
var form2 = new Form2();
form2.FormAction += form2_FormAction;
form2.Show();
}
private void form2_FormAction ( object o )
{
// Always returns reference to Form1
var form = this;
// If Form1 is open, button1.Parent is equal to form/this
// If Form1 is closed, button1.Parent is null
var parent = button1.Parent;
}
}
Form2:
public partial class Form2 : Form
{
public Form2 ()
{
InitializeComponent();
}
public delegate void FormActionHandler ( object o );
public event FormActionHandler FormAction = delegate { };
private void button1_Click ( object sender , EventArgs e )
{
FormAction( "Button clicked." );
}
}
理想情况下,我希望避免将事件引发到已关闭/已处理的表单(我不确定这是否可能),或者在调用者中找到一种干净的处理方式(在本例中为 Form1)。
感谢任何帮助。
【问题讨论】:
标签: c# winforms events delegates