我必须创建一个继承自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"并用我的替换?
谢谢
答案 0 :(得分:1)
你不能。
如果您正在尝试修改默认处理程序的功能,请忘记它,不能。如果您想添加您自己的行为,那么您可以创建一个新的处理程序并订阅该事件。
答案 1 :(得分:1)
您无需替换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);
}
}
答案 2 :(得分:1)
假设我们有方案
class BaseClass { public void M() { Console.WriteLine("BaseClass"); } }
class SubClass { public new void M() { Console.WriteLine("SubClass"); } }
void Main() {
var x = new SubClass();
x.M(); // Prints "SubClass"
((BaseClass)x).M(); // Prints "BaseClass"
}
在第一种情况下,它会调用SubClass.M
,在第二种情况下会调用BaseClass.M
。这就是“新”的含义 - 它创造了一种新方法。
但是,如果我们将BaseClass.M
虚拟并标记为SubClass.M
作为覆盖,那么它们都将打印“SubClass”,因为虚拟调用会检查运行时类型呼叫者。这就解释了为什么你的活动永远不会被提出。
正如IllidanS4所建议的那样,最好的方法是向FileSystemWatcher.Created
添加一个监听器,并将其调用LocalFolderWatcher
。
答案 3 :(得分:0)
您可以在FileSystemWatcher中订阅OnCreated事件,然后调用您自己的方法