不熟悉声明和使用事件以及收到错误,
事件必须是委托类型
基本上希望将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
}
}
答案 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) { ... }