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

C#通过一个事件从多个对象路由事件,c#,events,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 th

因此,我正在使用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类
{ 
公共代理void FooDel(字符串blah);
公共事件FooDel foodhandler;
//…最终引发FooHandler事件的某些代码
}
公共B级
{
公共A=新A();
//…调用“a”上函数的某些代码可能导致
//要引发的FooHandler事件
}
公共C类
{
私有列表MyListofBs=新列表();
//…导致将B的实例添加到列表中的代码
//并在可能引发A.foodhandler的那些B实例上调用函数
公共事件A.FooDel foodhandler;
}
我试图弄清楚的是如何将A实例的所有
A.foodhandler
事件触发路由到一个事件
C.foodhandler
。因此,如果有人注册到
C.foodhandler
,他们将真正获得由列表中B的实例所包含的A的任何实例引发的事件


我将如何实现这一点?

使用您提供的示例代码,您不能做您想要做的事情。由于您已在
B
内将
A
设为私有,因此您将从
B
类(包括
C
类)之外的任何代码中封锁对
A
实例的访问

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


Edit:假设B.a是公共的,因为
C.MyListofBs
是私有的,最简单的方法是创建自己的添加/删除方法,这些方法还可以订阅和取消订阅a中所需的事件,如下所示

我还冒昧地删除了您的代表,以支持更干净的班级


订阅B.foodhandler事件

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(); 
}

查看下面的示例

好吧,假设B中的“a”是公共的。但是现在C中没有我可以订阅的事件,这就是我的目标。很简单,只需添加事件并调用它即可。看我的最新编辑。啊,我想到过这样的事情,但是我想知道是否有一种直接的路由方式,比如以某种特殊的方式定义C.RelayEvent的添加和删除。如果你觉得有冒险精神,你可以反编译一些WPF库,并弄清楚Microsoft如何处理其隧道/冒泡路由事件。这一foreach将走向何方?在C中将所有B添加到列表中之后,会发生这种情况吗?什么是EventHandler,定义在哪里?是的,您可以在创建所有列表或添加每个项目后订阅
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);
        }
    }
}
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(); 
}