gpt4 book ai didi

c# - 如何避免将事件提升为封闭形式?

转载 作者:行者123 更新时间:2023-11-30 14:19:26 25 4
gpt4 key购买 nike

我在处理将事件提升为封闭形式的情况时遇到问题,希望得到一些帮助。

场景(引用下面代码):

  1. Form1 打开 Form2
  2. Form1 订阅了 Form2 上的事件(我们称该事件为 FormAction)
  3. Form1 关闭,Form2 保持打开状态
  4. Form2 引发 FormAction 事件

Form1.form2_FormAction 中,为什么 this 返回对 Form1 的引用,而 button1.Parent 返回 ?他们不应该都返回相同的引用吗?

如果我们要省略第 3 步,thisbutton1.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).

感谢任何帮助。

最佳答案

当您关闭 form1 时,您应该取消订阅该事件:

form2.FormAction -= form2_FormAction;

关于c# - 如何避免将事件提升为封闭形式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2675834/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com