问题提出一个简单的事件

时间:2015-02-11 15:59:16

标签: c# events .net-4.0 raiseevent

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

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

我收到以下编译错误

  

事件'ConsoleApplication1.IMyInterface.OnSomethingHappened'可以   仅出现在+ =或 - =

的左侧

我做错了什么?

1 个答案:

答案 0 :(得分:2)

这是您的代码的外观:

    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'在其中,因为它不是一个抽象类。