gpt4 book ai didi

c# - 事件触发事件

转载 作者:行者123 更新时间:2023-11-30 15:47:42 28 4
gpt4 key购买 nike

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

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

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

将发件人从触发对象更改为 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; }
}
}
}

最佳答案

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

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

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

关于c# - 事件触发事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3311271/

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