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



基本上想将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
    }
}

最佳答案

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

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) { ... }

10-04 12:05