0

所以我正在使用 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.FooHandlerA 实例的所有事件触发路由到一个 event C.FooHandler。因此,如果有人注册,C.FooHandler他们真的会收到由列表中 B 的实例包含的任何 A 实例引发的事件。

我将如何做到这一点?

4

2 回答 2

1

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

您必须以某种方式使您的A实例可公开访问,以便其中的方法C可以访问它B,以便订阅和取消订阅A.


编辑:假设 Ba 是公开的,因为是私有的,所以最简单的事情C.MyListofBs是创建自己的 Add/Remove 方法,这些方法也订阅和取消订阅 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);
        }
    }
}
于 2013-03-21T19:09:22.977 回答
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(); 
}

浏览以下示例事件教程

于 2013-03-21T19:10:55.853 回答