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

前端 未结 6 1315
庸人自扰
庸人自扰 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:58

    Wrap it with a protected virtual On... method:

    public class BaseClass
    {
        public event EventHandler SomeEvent;
    
        protected virtual void OnSomeEvent()
        {
            if(SomeEvent!= null)
                SomeEvent(this, new MyArgs(...) );
        }
    }
    

    Then override this in a derived class

    public class DerivedClass : BaseClass
    {
        protected override void OnSomeEvent()
        {
            //do something
    
            base.OnSomeEvent();
        }
    }
    

    You'll set this pattern all over .Net - all form and web controls follow it.

    Do not use the prefix Raise... - this is not consistent with MS's standards and can cause confusion elsewhere.

提交回复
热议问题