使 btn_Click 事件静态化 [英] making btn_Click event static

查看:32
本文介绍了使 btn_Click 事件静态化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有一个私有的 void btnContBalloon_Click(object sender, EventArgs e).我可以将其设为静态,因为我想从静态方法中调用它,但我不能.

There is a private void btnContBalloon_Click(object sender, EventArgs e). Can I make this static because I want to invoke this from static method but I can not.

推荐答案

使事件静态化是一种很好的解决方案.静态事件具有无限的生命周期.这使得您为事件注册的任何事件处理程序也永远存在.这使得包含此类事件处理程序的任何表单也永远存在.泄漏.

Making events static is a great way to shoot the foot. A static event has an unlimited life-time. Which makes any event handlers you register for the event live forever too. Which makes any form that contains such an event handler live forever too. A leak.

为静态事件注册事件处理程序需要在 FormClosing 事件处理程序中使用代码,例如明确取消注册处理程序的代码.您可以在有关 SystemEvents 类的 MSDN 库文章中看到这一点,这是 .NET 框架中具有静态事件的类的少数示例之一.

Registering an event handler for a static event requires code in, say, the FormClosing event handler that explicitly unregisters the handler. You can see this explicitly documented in the MSDN Library article for the SystemEvents class, one of the few examples of a class in the .NET framework that has static events.

更好的方法是跟踪应激活其按钮的 Click 事件的表单实例.像这样:

The better approach is to keep track of the form instance whose button's Click event should be activated. Something like this:

  public partial class Form1 : Form {
    public static Form1 MainForm { get; private set; }
    public Form1() {
      InitializeComponent();
      MainForm = this;
    }
    public void RunClickMethod() {
      button1.PerformClick();
    }
    protected override void OnFormClosing(FormClosingEventArgs e) {
      MainForm = null;
      base.OnFormClosing(e);
    }
  }

允许客户端代码执行此操作:

Which allows client code to do this:

  Form1.MainForm.RunClickMethod();

这篇关于使 btn_Click 事件静态化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆