引发一个简单事件的问题

Issue raising a simple event

我的界面有一个没有参数的事件

public interface IMyInterface
{
     event EventHandler OnSomethingHappened;
}

下面是我的实现方式。

   public class MyBaseClass : IMyInterface
    {
private event EventHandler onSomethingHappened;
public event EventHandler OnSomethingHappened
{
    add
    {
        onSomethingHappened-= value;
        onSomethingHappened+= value;
    }

    remove
    {
        onSomethingHappened-= value;
    }
}
    }

但是当我尝试按如下方式使用它时出现了其他情况

if ( MyBaseClassInstance.OnSomethingHappened != null )
        MyBaseClassInstance.OnSomethingHappened();

我得到以下编译错误

The event 'ConsoleApplication1.IMyInterface.OnSomethingHappened' can only appear on the left hand side of += or -=

我做错了什么?

您的代码可能是这样的:

    public interface IMyInterface
    {
        event EventHandler OnSomethingHappened;
    }

    //implement the interface
    public class MyBaseClass : IMyInterface
    {
        public event EventHandler OnSomethingHappened;

        public void DoSomeLogicWhichRaisesTheEvent()
        {
            if (OnSomethingHappened != null)
            {
                MyBaseClass sender = this;
                var eventArgs = new EventArgs();
                //let all subscibers to event know that the event happened
                OnSomethingHappened(sender, eventArgs);
            }
        }
    }

    public class ConsumerClass
    {
        private IMyInterface myBaseClassInstance;

        public ConsumerClass()
        {
            myBaseClassInstance = new MyBaseClass();
            //attach to the event
            myBaseClassInstance.OnSomethingHappened += MyBaseClassInstance_OnSomethingHappened;
        }

        private void MyBaseClassInstance_OnSomethingHappened(object sender, EventArgs e)
        {
            //react to the raised event
            throw new NotImplementedException();
        }
    }

如您所见,您需要实现 IMyInterface 接口,当 MyBaseClass 需要引发您调用 OnSomethingHappened(sender, eventArgs) 的事件时;

ConsumerClass 是您需要消费或做某事的地方,作为对引发事件的反应。 您可以考虑将 MyBaseClass 重命名为其他名称,其中不包含 'Base',因为它不是抽象的 class.