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

本文关键字:构造函数 继承 然后 调用 事件 方法 | 更新日期: 2023-09-27 18:22:20

我在C#中似乎遇到了构造函数、继承和事件订阅的问题。

考虑以下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();
        }
    }
}

我想要的是显示文本。即,我想将继承的基方法订阅到基类中的事件,然后能够调用子类中的构造函数,并在该事件被激发时调用子类的"事件方法"而不是基类。

有办法做到这一点吗?

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

您需要设置方法virtual:

public class Base
{...       
    public virtual void myEvent() { }

并覆盖

    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()

这将创建一个事件。你不想那样。在基类中生成事件virtual,并在此处使用override而不是new

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

 public virtual void myEvent() { }