我有一个调用另一个类的类-新类具有我为其定义的事件。我已在我的调用类中订阅了事件,但我的调用类似乎无法获取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);
}
}
答案 0 :(得分:1)
您有几个问题。您的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
参数的所有属性。这是一个非常标准的事件生产者/消费者模型。