使用您提供的示例代码,您无法做您想做的事。由于您已在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);
}
}
}