【发布时间】:2015-03-25 09:08:16
【问题描述】:
假设我有 2 个 WinForms:Form1 类的 f1 和 Form2 类的 f2。我想要做的是:通过单击 f1 上的 button1,应用程序将处理 f1 并运行 f2。这是代码:
//Form1
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent;
}
public delegate void EH_ChangeForm(object sender, EventArgs e);
//this defines an event
public static event EH_ChangeForm ChangeForm;
private void button1_Click(object sender, EventArgs e)
{
//this raises the event
ChangeForm(this, new EventArgs()); // NRC happens here!!! Zzz~
}
}
//Program
static class Program
{
static Form1 f1;
static Form2 f2;
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
f1 = new Form1();
f2 = new Form2();
Application.Run(f1);
//this subscribers to the event
Form1.ChangeForm += Form1_ChangeForm;
}
static void Form1_ChangeForm(object sender, EventArgs e)
{
f1.Dispose();
Application.Run(f2);
}
}
问题是:通过单击按钮 1,程序在尝试引发事件时会很糟糕(行“ChangeForm(this, new EventArgs());”) .发生 NullReferenceException,“this”指向 Form1 而不是 f1。
更一般地说,我应该如何在类之间使用事件?即,一个类对象应该如何订阅另一个类对象引发的事件?
【问题讨论】:
-
您完全不必担心如何处理,也不必使用
Application.Run打开表单,有Show和ShowDialog可以做到这一点 -
不清楚你所说的“this”是指Form1而不是f1是什么意思。”
-
也不清楚为什么您选择创建自己的委托类型,其签名与
EventHandler... -
this代表当前实例。如果您不将部分类与静态类、静态事件和在随机位置显式处置混合使用,那么所有这些都将更容易调试。是什么导致 NRE? -
@Jon Skeet:我要传输的是一个对象,但是“this”指向的是类,而不是对象。这个程序只是一个测试,为了方便起见,我只是没有定义任何特殊的委托。
标签: c# winforms class events this