所有具有特定接口的 类 都应通过事件通知

All classes with particular Interface should be notify by event

如何调用由接口声明的事件,以便通知所有已实现该接口的 classes?

例如在这样的结构中,

public delegate void myDel(int value);

interface IEventCaller{
event myDel myDelEventCall;
}


public Class One : IEventCaller {

public event myDel myDelEventCall;



}


public Class Two : IEventCaller {

public event myDel myDelEventCall;

}

我希望 class 一和二都得到通知并在事件被调用时采取行动,我感觉我走错了方向,可以吗?

其实你要的不涉及事件。实现 IEventCaller 的对象将使用事件来通知持有对该对象的某些更改的引用的某个对象。要在实现 IEventCaller 的对象上调用某些东西只需要一个方法,例如 Hello();

首先,您需要代码通知所有实现此接口的对象。为此,您需要在某处存储一个实例列表,希望 收到通知。

一个解决方案是创建一个 class 来管理该列表。这么说吧

private static List<IEventCaller> eventCallers = new List<IEventCaller>();

public static void AddEventCaller(IEventCaller c)
{
    eventCallers.Add(c);
}

public static void RemoveEventCaller(IEventCaller c)
{
    eventCallers.Remove(c);
}

public static IEventCaller[] EventCallers
{
    get { return eventCallers.ToArray() }
}

当然,此代码需要线程安全等。我将所有这些都放入 singleton 中以供全局使用。

然后,所有实现 IEventCallers 的对象都需要相应地 register/unregister。因此,我也让他们实现 IDisposable 以便在构造函数中你可以做

public EventCallable()
{
     Singleton.Instance.AddEventCaller(this);
}

Dispose 方法中,您可以这样做:

public void Dispose(bool disposing)
{
    Singleton.Instance.RemoveEventCaller(this);
}

现在应该通知每个实例的代码可以这样做:

public void NotifyAll()
{
    foreach (IEventCaller caller in Singleton.Instance.EventCallers)
        caller.Hello();
}

我想你可能正在看另一个。

对于事件,你希望有一个对象是 publisher,它负责发布事件并说 "hey guys, something just occurred and you should know about it",你有你的订阅者,他们说 "Yo dawg, let me know when that thing occurs, so i can act on it".

您可以做的是让负责事件发生的对象实现您的接口:

public class Publisher : IEventCaller
{
    public event MyDel MyDeleteEvent;
    public void OnDeleteOccured()
    {
        var myDeleteEvent = MyDeleteEvent;
        if (myDeleteEvent != null)
        {
            MyDeleteEvent(1);
        }
    }
}

然后让您的 OneTwo 对象注册到发生的事件,在那里它们传递一个方法,该方法的签名与 MyDel:

的委托类型相匹配
public class SubscriberOne
{
    public void OnSomethingOccured(int value)
    {
        Console.WriteLine(value);
    }
}

public class SubscriberTwo
{
    public void OnSomethingOccured(int value)
    {
        Console.WriteLine(value);
    }
}

然后注册:

void Main()
{
    var publisher = new Publisher();
    var subscriberOne = new SubscriberOne();
    var subscriberTwo = new SubscriberTwo();

    publisher.MyDeleteEvent += subscriberOne.OnSomethingOccured;
    publisher.MyDeleteEvent += subscriberTwo.OnSomethingOccured;
}