我必须创建一个继承自 FileSystemWatcher
的类。我应该拦截事件 OnCreated
并创建我自己的事件 OnCreated
。我试过如下:
public class LocalFolderWatcher : FileSystemWatcher, IWatcher
{
...
public event LocalFolderEventHandler Created;
protected override void OnCreated(FileSystemEventArgs e)
{
string path = System.IO.Path.GetDirectoryName(e.FullPath);
LocalFolderEventArgs args = new LocalFolderEventArgs(e.ChangeType, this._gatewayConfigurationName, path, this._folderConfigurationName, e.Name);
if (Created != null && base.EnableRaisingEvents && base.Path != null)
Created(this, args);
base.OnCreated(e);
}
}
但我得到一个错误:我无法覆盖未标记为虚拟、抽象或覆盖的方法。我试图用"new"替换“覆盖”,但这样就不会引发事件..
如何拦截真正的“OnCreated”并替换为我的?
谢谢
最佳答案
您不需要替换OnCreated
,只需创建您自己的处理程序并将其传递给Created
事件即可。
public class LocalFolderWatcher : FileSystemWatcher, IWatcher
{
//...
public event LocalFolderEventHandler CustomCreated;
public LocalFolderWatcher()
{
Created += OnCreated;
}
private new void OnCreated(object sender, FileSystemEventArgs e)
{
string path = System.IO.Path.GetDirectoryName(e.FullPath);
LocalFolderEventArgs args = new LocalFolderEventArgs(e.ChangeType, this._gatewayConfigurationName, path, this._folderConfigurationName, e.Name);
if (CustomCreated != null && base.EnableRaisingEvents && base.Path != null)
CustomCreated(this, args);
}
}
关于c# - 如何覆盖未标记为虚拟的事件处理程序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26993360/