gpt4 book ai didi

c# - 解释用户控件中自定义事件的代码

转载 作者:太空狗 更新时间:2023-10-29 20:08:48 24 4
gpt4 key购买 nike

有人给了我这段代码,效果很好。但我真的很想了解里面发生了什么。有人可以解释一下吗?代码各部分的含义是什么?该代码位于自定义控件内,该控件在面板内有两个标签。

我还看到了一些使用添加/删除语法的自定义控件事件,那是干什么用的?与这里发生的事情有什么区别?

public partial class UserControl1 : UserControl
{
public UserControl1()
{
InitializeComponent();
}

public event EventHandler MyCustomClickEvent;

protected virtual void OnMyCustomClickEvent(EventArgs e)
{
// Here, you use the "this" so it's your own control. You can also
// customize the EventArgs to pass something you'd like.

if (MyCustomClickEvent != null)
MyCustomClickEvent(this, e);
}

private void label1_Click(object sender, EventArgs e)
{
OnMyCustomClickEvent(EventArgs.Empty);
}
}

最佳答案

请参阅下面我的评论。同样对于更详细的事件我blogged前段时间我在这个概念上详细介绍了整个过程。

public partial class UserControl1 : UserControl
{
//This is the standard constructor of a user control
public UserControl1()
{
InitializeComponent();
}

//This defines an event called "MyCustomClickEvent", which is a generic
//event handler. (EventHander is a delegate definition that defines the contract
//of what information will be shared by the event. In this case a single parameter
//of an EventArgs object.
public event EventHandler MyCustomClickEvent;


//This method is used to raise the event, when the event should be raised,
//this method will check to see if there are any subscribers, if there are,
//it raises the event
protected virtual void OnMyCustomClickEvent(EventArgs e)
{
// Here, you use the "this" so it's your own control. You can also
// customize the EventArgs to pass something you'd like.

if (MyCustomClickEvent != null)
MyCustomClickEvent(this, e);
}

private void label1_Click(object sender, EventArgs e)
{
OnMyCustomClickEvent(EventArgs.Empty);
}
}

关于c# - 解释用户控件中自定义事件的代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3998479/

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