2015-02-11 49 views
-1

我的接口有不有一個參數問題提出一個簡單的事件

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; 
    } 
} 
    } 

但somehwere否則當我嘗試如下

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

我獲得以下編譯錯誤

事件 'ConsoleApplication1.IMyInterface.OnSomethingHappened' 可以 只出現在使用它+ =或 - 的左側=

我做錯了什麼?

+0

'MyBaseClass'是**不**實現'IMyInterface'。關於錯誤,請搜索它,例如[這裏](http://stackoverflow.com/q/4496799/1997232)是同樣的問題。 – Sinatr 2015-02-11 16:15:47

+0

thakns我試過這樣做,但繼續得到相同的錯誤。更新我的問題以瞭解我所做的更改 – 2015-02-11 16:24:40

回答

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事件(發件人,EventArgs的);

ConsumerClass是您需要消費或做某事的地方,作爲對所引發事件的反應。 您可能會考慮將MyBaseClass重命名爲其他名稱,但不包含「Base」,因爲它不是抽象類。

+0

您能否簡要解釋此代碼中發生了什麼以及如何解決問題? – anaximander 2015-02-11 16:34:18

+0

我已經更新了答案 – 2015-02-11 16:42:01