简体   繁体   English

如何取消订阅装饰器中的事件

[英]How to unsubscribe from event in decorator

I have base abstract class and derived class from it. 我有基础抽象类和从其派生的类。 When I call Method1() from derived class there is a subscription on Event. 当我从派生类调用Method1()时,有一个Event订阅。 I need to create decorator for derived class and replace some functionality and I don't need that Method1() from base class was called. 我需要为派生类创建装饰器并替换某些功能,并且不需要从基类调用Method1()。 So I tried to cancel it subscription in construct of decorator but it doesn't work. 所以我试图取消装饰器构造中的订阅,但它不起作用。 The structure of base and derived code is legacy. 基本代码和派生代码的结构是遗留的。

    abstract class Base {
        public event Action Event;
        public abstract void Method1();
        public virtual void Method2(){ Console.WriteLine("Base Method2 call"); }
        public void OnEventInvoke() { Event?.Invoke();}
    }

    class Derived : Base{
        public override void Method1() { Event += Method2;}
    }

    class Decorator: Base {
        private Base b;
        public Decorator(Base b){
            this.b = b;
            b.Event -= base.Method2;
            b.Event += Method2;
        }
        public override void Method1(){}
        public override void Method2(){Console.WriteLine("Decorator Method2 call");}
    }

    static void Main(string[] args){
        var derived = new Derived();
        derived.Method1();
        derived.OnEventInvoke();
        var decorator = new Decorator(derived);
        decorator.OnEventInvoke();  //need "Decorator Method2 call"
    }

Is it possible to unsubscribe from base.Method2 in decorator and subscribe with decorator.Method2? 是否可以在decorator中取消订阅base.Method2并通过decorator.Method2进行订阅?

So your solution is calling the OnEventInvoke of the decorator, but you are modifying the subscriptions to member. 因此,您的解决方案是调用装饰器的OnEventInvoke,但您正在修改成员的订阅。 If you want to keep the composition you could do the following: 如果要保留组成,可以执行以下操作:

class Decorator : Base
{
    private Base b;
    public Decorator(Base b)
    {
        this.b = b;
        b.Event -= b.Method2;
        b.Event += Method2;
    }
    public override void Method1() { }
    public override void Method2() { Console.WriteLine("Decorator Method2 call"); }

    public override void OnEventInvoke()
    {
        b.OnEventInvoke();
    }
}

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

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