是否将事件添加到另一个事件?c#

是否将事件添加到另一个事件?c#,c#,events,C#,Events,上面的(伪)代码工作正常,编译良好 但是,如果我将bar更改为public event Action bar,则无法将其添加到foo。 基本上,我想将一个事件添加到另一个事件。我知道这听起来有点可笑。 如果bar是公共事件,则使用lambda调用bar事件: class a { public event Action foo; var zzz = new b(); foo += zzz.bar; } class b { public Action bar;

上面的(伪)代码工作正常,编译良好

但是,如果我将
bar
更改为
public event Action bar
,则无法将其添加到
foo
。 基本上,我想将一个事件添加到另一个事件。我知道这听起来有点可笑。

如果bar是公共事件,则使用lambda调用bar事件:

class a 
{
    public event Action foo;
    var zzz = new b();
    foo += zzz.bar;
}

class b 
{
    public Action bar;
}
这不是确切的语法,正在研究。。。

这是不可能的,因为不能从定义bar事件的类之外调用它

你应该使用这样的解决方案

foo += () => zzz.bar();

然后您可以使用InvokeBar作为事件的目标。

IIRC您不能直接从另一个类调用事件

class b {
    public Action bar;
    public void InvokeBar() {
       if (bar != null) bar();
    }
}

你想要达到的目标是这样的(我猜):

  • foo
    事件被触发:
    调用所有
    foo
    subscribed事件处理程序加上所有
    bar
    subscribed事件处理程序
  • 被触发:
    调用所有
    bar
    subscribed事件处理程序加上所有
    foo
    subscribed事件处理程序

  • 注意事项:

    此代码(如果(1)和(2)选项均已启用)会导致无限次呼叫,即:

    class a 
    {
        public event Action foo;
        b zzz = new b();
        public a()
        {
            // this allow you to achieve point (1)
            foo += zzz.FireBarEvent;
            // this allow you to achieve point (2)
            zzz.bar += OnBar;
        }
        void OnBar()
        {
            FireFooEvent();
        }
        void FireFooEvent()
        {
            if(foo != null)
                foo();
        }
    }
    
    class b 
    {
        public event Action bar;
        public void FireBarEvent()
        {
           if(bar != null)
               bar();
        }
    }
    

    必须正确管理。

    我认为您的代码无法编译。他实际上写道,这是一种伪代码中介方法,为了可读性,我认为这种方法是最好的。@maxp:thx,请查看完整性警告;)是的,很烦人。您甚至不能从派生类调用它们。不过,您可以调用委托,因此使用委托的通用列表而不是事件几乎是值得的。
    class a 
    {
        public event Action foo;
        b zzz = new b();
        public a()
        {
            // this allow you to achieve point (1)
            foo += zzz.FireBarEvent;
            // this allow you to achieve point (2)
            zzz.bar += OnBar;
        }
        void OnBar()
        {
            FireFooEvent();
        }
        void FireFooEvent()
        {
            if(foo != null)
                foo();
        }
    }
    
    class b 
    {
        public event Action bar;
        public void FireBarEvent()
        {
           if(bar != null)
               bar();
        }
    }
    
    foo --> bar --> foo --> bar ...