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

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

    The standard practice here is to have a protected virtual method OnSomeEvent on your base class, then call that method in derived classes. Also, for threading reasons you will want to keep a reference to the handler before checking null and calling it.

    For an explanation of the why read Jon Skeet's answer or the C# specification which describes how the compiler automatically creates a private field.

    Here is one possible work around.

    public class A
    {
        public event EventHandler SomeEvent;
    
        public void someMethod()
        {
            OnSomeEvent();
        }
    
        protected void OnSomeEvent()
        {
            EventHandler handler = SomeEvent;
            if(handler != null)
                handler(this, someArgs);
        }
    }
    
    public class B : A
    {
        public void someOtherMethod()
        {
            OnSomeEvent();
        }
    }
    

    Edit: Updated code based upon Framework Design Guidelines section 5.4 and reminders by others.

提交回复
热议问题