简体   繁体   English

将继承的方法预订给构造函数中的事件,然后在继承的类中调用该构造函数

[英]Subscribing inherited methods to events in a constructor, then calling that constructor in an inherited class

I seem to have a problem in C# with constructors, inheritance and event subscription. 我在C#中似乎对构造函数,继承和事件订阅有问题。

Consider the following C# program: 考虑以下C#程序:

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. 我想要的是要显示的文本。 ie 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? 有什么办法吗?

You need to set the method virtual : 您需要将方法设置为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!");
    }
}
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. 使事件在基类中virtual ,并在此处使用override而不是new

将基类方法标记为虚方法,您的问题将得到解决。

 public virtual void myEvent() { }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM