【问题标题】:Event firing a event事件触发事件
【发布时间】:2010-07-23 01:00:55
【问题描述】:

我的班级中有一个私有对象。如果该对象触发一个事件,我想将该事件传递给正在使用我的类的任何东西。目前我是这样做的,我把我的构造函数:

cbName.CheckedChanged += ((sender, args) => this.CheckChanged(this,args));

有没有更好的方法来做到这一点,是否有任何陷阱,比如类不会被释放,因为它本身有一个事件,我需要在 dispose 函数中手动取消订阅?

将发送者从触发对象更改为this 是可选的。

完整版测试代码

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace placeholder
{
    internal class FilterBase : UserControl, IFilterObject
    {
        public FilterBase(string name)
        {
            InitializeComponent();
            cbName.CheckedChanged += ((sender, args) => this.CheckChanged(this,args));
            cbName.Name = name;
            this.Name = name;
        }

        private CheckBox cbName;
        /// <summary> 
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary> 
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Component Designer generated code

        /// <summary> 
        /// Required method for Designer support - do not modify 
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.cbName = new System.Windows.Forms.CheckBox();
            this.SuspendLayout();
            // 
            // cbName
            // 
            this.cbName.AutoSize = true;
            this.cbName.Location = new System.Drawing.Point(4, 4);
            this.cbName.Name = "cbName";
            this.cbName.Size = new System.Drawing.Size(79, 17);
            this.cbName.TabIndex = 0;
            this.cbName.Text = "Filter Name";
            this.cbName.UseVisualStyleBackColor = true;
            // 
            // UserControl1
            // 
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.AutoSize = true;
            this.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink;
            this.Controls.Add(this.cbName);
            this.Name = "Filter Name";
            this.Size = new System.Drawing.Size(86, 24);
            this.ResumeLayout(false);
            this.PerformLayout();

        }

        #endregion

        public event EventHandler CheckChanged;
        public bool Checked
        {
            get { return cbName.Checked; }
        }
    }
}

【问题讨论】:

    标签: c# events .net-4.0


    【解决方案1】:

    event 实际上类似于自动属性。您可以定义自己的 addremove 方法,将委托直接传递给子控件,从而消除额外的间接级别:

    public event EventHandler CheckChanged {
        add { cbName.CheckChanged += value; }
        remove { cbName.CheckChanged -= value; }
    }
    

    这将删除一个额外的 Delegate 存储在您的类中(因为 Delegate 字段在标准事件的幕后使用)

    【讨论】:

    • 酷,不知道。
    • 有什么办法可以让我的蛋糕也吃掉吗?使用类似的方法将发件人从 cbName 更改为 FilterBase?
    • 与往常一样,Jon Skeet 在这里有一篇关于事件运作的精彩文章:csharpindepth.com/Articles/Chapter2/Events.aspx。如果适用于您的情况,请务必了解线程安全。
    【解决方案2】:

    嗯,这将防止当前对象在cbName 还活着时被垃圾收集,但听起来这不太可能是一个问题......而且它固有的事实是你有一个对 @ 的引用987654322@ 无论你做什么(因为你想触发这个对象的 CheckChanged 处理程序)。

    这样做的一个缺点是您无法取消订阅(例如在 Dispose 方法中),即使您愿意。另一种方法是使用实​​际方法:

    private void CbNameCheckedChangedHandler(object sender, EventArgs e)
    {
        CheckedChanged(this, args);
    }
    
    ...
    cbName.CheckedChanged += CbNameCheckedChangedHandler;
    
    // If you ever want to remove the handler
    cbName.CheckedChanged -= CbNameCheckedChangedHandler;
    

    请注意,这一切都假设您的 CheckedChanged 事件是空安全的,例如它被声明为:

    public event EventHandler CheckedChanged = delegate {};
    

    否则,如果没有人订阅该事件,当cbName.CheckedChanged 触发时,您将获得一个NullReferenceException

    【讨论】:

    • 感谢空引用警告!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-24
    • 2014-09-18
    相关资源
    最近更新 更多