Monday, May 23, 2005

Chaining events in .Net (Sometimes it just isn't so easy)

The solution in my last blog post turned out to only be a semi-working solution since doing the "direct assignment" thingy:
that.MyEvent += this.MyEvent;
only copies the already registered event handlers, which seems perfectly normal when I think about it now. Besides that, the example in my last post was so fictional that it doesn't even work, so here's a working one that illustrates the copy functionality.

class Class1
{
[STAThread]
static void Main()
{
B b = new B();
A a = new A();
a.MyEvent += new X(a_MyEvent);
a.MyEvent += new X(a_MyEvent);
a.Chain(b);
a.MyEvent += new X(a_MyEvent);
b.Fire();
}

public delegate void X();

public class A
{
public event X MyEvent;

public void Chain(B b)
{
b.MyEvent += MyEvent;
}
}

public class B
{
public event X MyEvent;

public void Fire()
{
MyEvent();
}
}
private static void a_MyEvent() { Console.WriteLine("Yihaa!"); }
}

0 Comments:

Post a Comment

<< Home