C#通过一个事件从多个对象路由事件

时间:2013-03-21 18:55:36

标签: c# events

所以我正在使用C#3.0,而我正在尝试完成某种特定形式的事件路由。

public class A
{ 
  public delegate void FooDel(string blah);
  public Event FooDel FooHandler;

  //...some code that eventually raises FooHandler event
}

public class B
{
  public A a = new A(); 

  //...some code that calls functions on "a" that might cause
  //FooHandler event to be raised
}

public class C
{
  private List<B> MyListofBs = new List<B>();

  //...code that causes instances of B to be added to the list
  //and calls functions on those B instances that might get A.FooHandler raised

  public Event A.FooDel FooHandler;
}

我想弄清楚的是如何将A实例的所有A.FooHandler事件触发路由到一个事件C.FooHandler。因此,如果某人注册到C.FooHandler,他们将真正获得由列表中B实例包含的任何A实例引发的事件。

我将如何做到这一点?

2 个答案:

答案 0 :(得分:1)

使用您提供的示例代码,您无法执行所需的操作。由于您已在A内将B设为私有,因此您正在封锁A类以外B类之外的任何代码(包括C } class)。

您必须以某种方式公开访问A个实例,以便C中的方法可以通过B访问它,以便订阅和取消订阅A中包含的事件1}}。


编辑:假设Ba是公开的,自C.MyListofBs以来最简单的事情就是私有,就是创建自己的添加/删除方法,这些方法也订阅和取消订阅事件你想要在A中,就像这样。

我也冒昧地删除你的代表,转而支持更清洁的Action课程。

public class A
{ 
    public Event Action<string> FooHandler;

    //...some code that eventually raises FooHandler event
}

public class B
{
    public A a = new A();

    //...some code that calls functions on "a" that might cause
    //FooHandler event to be raised
}

public class C
{
    private List<B> MyListofBs = new List<B>();

    //...code that causes instances of B to be added to the list
    //and calls functions on those B instances that might get A.FooHandler raised

    public void Add(B item)
    {
        MyListofBs.Add(item);
        item.a.FooHandler += EventAction;
    }

    public void Remove(B item)
    {
        item.a.FooHandler -= EventAction;
        MyListofBs.Remove(item);
    }

    private void EventAction(string s)
    {
        // This is invoked when "A.FooHandler" is raised for any 
        // item inside the MyListofBs collection.
    }
}

修改如果您想要C中的接力事件,请执行以下操作:

public class C
{
    private List<B> MyListofBs = new List<B>();

    public event Action<string> RelayEvent;

    //...code that causes instances of B to be added to the list
    //and calls functions on those B instances that might get A.FooHandler raised

    public void Add(B item)
    {
        MyListofBs.Add(item);
        item.a.FooHandler += EventAction;
    }

    public void Remove(B item)
    {
        item.a.FooHandler -= EventAction;
        MyListofBs.Remove(item);
    }

    private void EventAction(string s)
    {
        if(RelayEvent != null)
        {
            RelayEvent(s);
        }
    }
}

答案 1 :(得分:0)

订阅您的B.foohandler活动

Foreach(var item in MyListofBs) 
{

      Item.fooHandler += new EventHandler(CEventHandler) 
}
   //each time your Events are called you reroute it with C.EventHandler 
Private CEventHandler(string blah) 
{    
    If(FooHanler!=null)
       FooHanler(); 
}

回顾以下示例Events Tutorial