class a
{
public event Action foo;
var zzz = new b();
foo += zzz.bar;
}
class b
{
public Action bar;
}
以上(伪)代码可以正常工作并编译。
但是,如果我将bar
更改为public event Action bar
,我就无法将其添加到foo
。
基本上我想将一个事件添加到另一个事件中。我知道这听起来很荒谬。
答案 0 :(得分:2)
IIRC你不能直接从另一个班级调用事件。
class A {
public A() {
b = new B(this);
}
private B b;
public event Action Foo;
}
class B {
public B(A a) {
a.Foo += InvokeBar;
}
public event Action Bar;
private void InvokeBar() {
if (Bar != null)
Bar();
}
}
答案 1 :(得分:1)
<击> 如果bar是公共事件,那么您使用lambda来调用bar事件:
foo += () => zzz.bar();
这不是确切的语法,研究......
击>
这是不可能的,因为你无法从定义它的类之外调用bar事件。
你应该使用这样的解决方案;
class b {
public Action bar;
public void InvokeBar() {
if (bar != null) bar();
}
}
然后,您可以使用InvokeBar作为事件的目标。
答案 2 :(得分:1)
你想达到的是这样的(我猜):
foo
事件被触发:foo
订阅的事件处理程序以及所有bar
订阅的事件处理程序。bar
被触发:bar
订阅的事件处理程序以及所有foo
订阅的事件处理程序。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();
}
}
<强> CAVEAT:强>
此代码(如果(1)和(2)选项都启用)会导致无限次调用,例如:
foo --> bar --> foo --> bar ...
必须妥善管理。