0

I seem to have a problem in C# with constructors, inheritance and event subscription.

Consider the following C# program:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace EventTest
{
    public class Widget
    {
        public delegate void MyEvent();
        public event MyEvent myEvent;

        public void SetEvent()
        {
            myEvent();
        }
    }

    public class Base
    {
        Widget myWidget;

        protected Base() { }

        protected Base(Widget awidget)
        {
            myWidget = awidget;
            myWidget.myEvent += myEvent;
        }

        public void myEvent() { }
    }

    public class Derived : Base
    {
        public Derived(Widget awidget) : base(awidget) { }

        new public void myEvent()
        {
            System.Console.WriteLine("The event was fired, and this text is the response!");
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            Widget myWidget = new Widget();
            Derived myDerived = new Derived(myWidget);

            myWidget.SetEvent();
        }
    }

}

What I want is for the text to be displayed. i.e. I want to subscribe an inherited base method to an event in base class, then be able to call the constructor in a subclass, and get the subclasses' event method to get called instead of the base classes' when that event is fired.

Is there any way to do this?

4

3 回答 3

1

You need to set the method virtual :

public class Base
{...       

    public virtual void myEvent() { }

And override it

    public class Derived : Base
{
    ...

    public override void myEvent()
    {
        System.Console.WriteLine("The event was fired, and this text is the response!");
    }
}
于 2013-07-15T16:24:26.823 回答
0
new public void myEvent()

This creates a new event. You don't want that. Make the event virtual in the base class and use override instead of new here.

于 2013-07-15T16:23:30.973 回答
0

Mark the base class method as virtual and your problem will be solved.

 public virtual void myEvent() { }
于 2013-07-15T16:24:13.597 回答