Why events can't be used in the same way in derived classes as in the base class in C#?

前端 未结 6 1323
庸人自扰
庸人自扰 2020-11-29 07:27

In following code, I want to extend the behaviour of a class by deriving/subclassing it, and make use of an event of the base class:

public class A
{
    pub         


        
6条回答
  •  孤街浪徒
    2020-11-29 07:53

    Todd's answer is correct. Often you will see this implemented throughout the .NET framework as OnXXX(EventArgs) methods:

    public class Foo
    {
        public event EventHandler Click;
    
        protected virtual void OnClick(EventArgs e)
        {
            var click = Click;
            if (click != null)
                click(this, e);
        }
    }
    

    I strongly encourage you to consider the EventArgs/EventHandler pattern before you find yourself making all manner of CustomEventArgs/CustomEventHandler for raising events.

提交回复
热议问题