在调用中获取 EventArgs class

Getting EventArgs in a calling class

我有一个 class 调用另一个 class - 新的 class 有我为它定义的事件。我在调用 class 中订阅了事件,但调用 class 似乎无法获取 EventArgs。我知道我一定是在做一些无知的事情,但我不知道是什么。

我的代码缩写如下。 WorkControl 是主进程并调用 MyProcess 执行一些代码并触发事件。

public class WorkControl
{
    public MyProcess myp;

    public WorkControl()
    {
            myp.InBoxShareDisconnected += OnShareFolderDisconnected();
        }

        private EventHandler OnShareFolderDisconnected<NetworkShareDisconnectedEventArgs>()
        {
          // How do I get my EventArgs from the event?
           throw new NotImplementedException();
        }

}

public class MyProcess
{
    public void MyDisconnectTrigger
    {
             NetworkShareDisconnectedEventArgs e = 
new NetworkShareDisconnectedEventArgs(path, timestamp, connected);

                OnInBoxShareDisconnected(e);
    }

        public event EventHandler<NetworkShareDisconnectedEventArgs> InBoxShareDisconnected;

        protected void OnInBoxShareDisconnected(NetworkShareDisconnectedEventArgs e)
        {
          //  InBoxShareDisconnected(this, e);
            InBoxShareDisconnected.SafeInvoke(this, e);
        }
}

你有几个问题。您的 MyProcess class 不应该在构造函数中引发事件,并且 MyWorker class 需要有一个 MyProcess 的实例来附加事件。另一个问题是您需要正确声明事件处理程序。

让我们看看适合您的制作人的事件模式 MyProcess class:

public class MyProcess
{
    public event EventHandler<NetworkShareDisconnectedEventArgs> InBoxShareDisconnected;

    public MyProcess()
    {
        //This doesn't really do anything, don't raise events here, nothing will be
        //subscribed yet, so nothing will get it.
    }

    //Guessing at the argument types here
    public void Disconnect(object path, DateTime timestamp, bool connected)
    {
        RaiseEvent(new NetworkShareDisconnectedEventArgs(path, timestamp, connected));
    }

    protected void RaiseEvent(NetworkShareDisconnectedEventArgs e)
    {
        InBoxShareDisconnected?.Invoke(this, e);
    }
}

现在我们可以查看您的消费者 class:

public class WorkControl
{
    private MyProcess _myProcess;

    public WorkControl(MyProcess myProcess)
    {
        _myProcess = myProcess;  //Need to actually set it to an object
        _myProcess.InBoxShareDisconnected += HandleDisconnected;
    }

    private void HandleDisconnected(object sender, NetworkShareDisconnectedEventArgs e)
    {
        //Here you can access all the properties of "e"
    }
}

现在您可以使用消费者 class 中的事件并访问 NetworkShareDisconnectedEventArgs 参数的所有属性。这是一个非常标准的事件 producer/consumer 模型。