【问题标题】:why "this" points to class rather than class object? [closed]为什么“this”指向类而不是类对象? [关闭]
【发布时间】: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 打开表单,有ShowShowDialog 可以做到这一点
  • 不清楚你所说的“this”是指Form1而不是f1是什么意思。”
  • 也不清楚为什么您选择创建自己的委托类型,其签名与EventHandler...
  • this 代表当前实例。如果您不将部分类与静态类、静态事件和在随机位置显式处置混合使用,那么所有这些都将更容易调试。是什么导致 NRE?
  • @Jon Skeet:我要传输的是一个对象,但是“this”指向的是类,而不是对象。这个程序只是一个测试,为了方便起见,我只是没有定义任何特殊的委托。

标签: c# winforms class events this


【解决方案1】:

您获得NullReferenceException 的原因是没有向您的Form1.ChangeForm 注册事件处理程序,因为Application.Run 等待实例f1 停止接收消息。

您需要在 Main 方法中交换两行,如下所示:

 Form1.ChangeForm += Form1_ChangeForm;
 Application.Run(f1);

始终尝试“尽可能快地”注册事件处理程序,这样您就不会执行某些操作并期望在没有人监听时执行事件。

另外,在编写事件调用器时,请尝试使用缓存事件然后调用它的模式

private void FireChangeForm() {
    var handler = ChangeForm;
    if (handler != null) {
        handler(this, new EventArgs());
    }
}

因此,您也可以避免任何竞争条件。请阅读 Eric Lippert 的博客文章 Events and Races,了解为什么要这样做。

【讨论】:

  • 它有效。非常感谢!
  • @Patrick:感谢您的解释,我真的很感激!
猜你喜欢
  • 2016-07-08
  • 2015-05-30
  • 1970-01-01
  • 1970-01-01
  • 2020-08-19
  • 2013-12-30
  • 2010-10-13
  • 2011-09-22
相关资源
最近更新 更多