事件必须是委托类型?

时间:2015-11-05 15:39:16

标签: c#

不熟悉声明和使用事件以及收到错误,

  

事件必须是委托类型

基本上希望将IMyInterface作为依赖项传递给另一个类,该类可以订阅接收MyClassEvent个事件,事件数据为MyClass

public interface IMyInterface
{
   event MyClass MyClassEvent;
}

public class Implementation: IMyInterface
{
     event MyClass MyClassEvent;
     public void OnSomethingHappened
     {
         MyClassEvent?.Invoke(); // pass MyClass to subscribers
     }
}

public class AnotherClass(IMyInterface ...)
{
    OnMyClassEvent(MyClass args)
    {
       // do something
    }
}

1 个答案:

答案 0 :(得分:6)

您需要正确声明事件并定义事件参数:

public class MyClassEventArgs : EventArgs { }

public interface IMyInterface
{
    event EventHandler<MyClassEventArgs> MyClassEvent;
}

public class Implementation : IMyInterface
{
    public event EventHandler<MyClassEventArgs> MyClassEvent;

    public void OnSomethingHappened()
    {
        MyClassEvent?.Invoke(this, new MyClassEventArgs());
    }
}

订阅它:

var implementation = new Implementation();
implementation.MyClassEvent += MyClassEvent;

private void MyClassEvent(object sender, MyClassEventArgs e) { ... }