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

Ver*_*onW 7 c# events user-controls winforms

有人给了我这个代码很好的代码.但我真的很想了解其中发生的事情.有人可以解释一下吗?代码的每个部分的含义是什么?代码位于自定义控件内,该控件在面板内有两个标签.

此外,我已经看到一些使用添加/删除语法的自定义控件事件,这是为了什么?与这里发生的事情有什么不同?

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

Mit*_*ers 8

请参阅下面的评论.另外,对于一个更详细的事件,我在这个概念的博客上回顾了整个过程的更多细节.

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);
    }
}
Run Code Online (Sandbox Code Playgroud)