簡體   English   中英

在調用類中獲取EventArgs

[英]Getting EventArgs in a calling class

我有一個調用另一個類的類-新類具有我為其定義的事件。 我已在我的調用類中訂閱了事件,但我的調用類似乎無法獲取EventArgs。 我知道我必須在這里做些無知的事情,但我不知道該怎么做。

我的代碼在下面縮寫。 WorkControl是主要進程,並調用MyProcess,該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類不應在構造函數中引發事件,並且MyWorker類需要具有MyProcess的實例才能將事件附加到該實例。 另一個問題是您需要正確聲明事件處理程序。

讓我們看看生產者MyProcess類的正確事件模式:

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

現在我們可以看看您的消費者類別:

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

因此,現在您可以使用使用者類中的事件,並可以訪問NetworkShareDisconnectedEventArgs參數的所有屬性。 這是一個非常標准的事件生產者/消費者模型。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM