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

时间:2013-07-15 16:20:22

标签: c# events inheritance constructor subscription

我在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();
        }
    }

}

我想要的是显示文字。即我想在基类中为一个事件订阅一个继承的基本方法,然后能够在子类中调用构造函数,并在触发该事件时获取子类的事件方法来调用而不是基类。 / p>

有没有办法做到这一点?

3 个答案:

答案 0 :(得分:1)

您需要将方法设置为虚拟:

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!");
    }
}

答案 1 :(得分:0)

new public void myEvent()

这会创建事件。你不希望这样。在基类中制作活动virtual并在此处使用override代替new

答案 2 :(得分:0)

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

 public virtual void myEvent() { }