为什么子项不能覆盖其父项中的事件订阅?

时间:2013-11-12 14:11:51

标签: c# events inheritance

这是一个示例代码,在使用虚拟方法和覆盖时无法正常工作。为什么呢?

main()
{
    Child c = new Child();
    c.Trigger = new Trigger();
}

public class Parent
{
    public Trigger _trigger;

    public Trigger Trigger
    {
        set 
        {
            _trigger = value;
            _trigger.TriggerEvent += Trigger.TriggerHandler(OnTrigger);
        }
    }

    internal virtual void OnTrigger(int type)
    {
        Write("I don't want to write this!");
    }
}

public class Child : Parent
{
    internal override void OnTrigger(int type)
    {
        Write("I want this to be written, but it's not.");
    }
}

不会覆盖订阅父级中事件的方法“OnTrigger”。如何在父项中订阅的事件执行子方法?

2 个答案:

答案 0 :(得分:0)

以下代码是您想要的吗?

    public class Trigger
    {
        public event Action TriggerEvent;

        public void NotifyTrigger()
        {
            this.TriggerEvent();
        }
    }

    public class Parent
    {
        public Trigger _trigger;

        public Trigger Trigger
        {
            get
            {
                return _trigger;
            }

            set
            {
                _trigger = value;
                _trigger.TriggerEvent += this.OnTrigger;
            }
        }

        internal virtual void OnTrigger()
        {
            Debug.WriteLine("I don't want to write this!");
        }
    }

    public class Child : Parent
    {
        internal override void OnTrigger()
        {
            Debug.WriteLine("I want this to be written, but it's not.");
        }
    }

    [Test]
    public void testetst() // Or Main
    {
        Child c = new Child();
        c.Trigger = new Trigger();
        c.Trigger.NotifyTrigger();
    }

这对我有用。输出是:“我想要写这个,但事实并非如此。”

答案 1 :(得分:0)

我在其他地方发现了这个问题。在这种情况下,Child1.Trigger应该影响Child子实例,但不是调用child.Trigger.NotifyTrigger()(使用Yohanes的示例),而是调用它自己的(this.Trigger.NotifyTrigger),Child1没有覆盖OnTrigger!