我正在编写涉及FileSystemWatcher对象的集成测试。为了使事情变得更容易,我想取消订阅活动委托中的所有内容,而不必搜索每个订阅。我已经看到相关的帖子,Is it necessary to unsubscribe from events?。这有点重复,但我特别问为什么这不适用于FileSystemWatcher对象。FileSystemWatcher事件通过System.Delegate不可触发吗?
这将是很好做类似如下:
private void MethodName()
{
var watcher = new FileSystemWatcher(@"C:\Temp");
watcher.Changed += new FileSystemEventHandler(watcher_Changed);
watcher.Changed = null; // A simple solution that smells of C++.
// A very C#-ish solution:
foreach (FileSystemEventHandler eventDelegate in
watcher.Changed.GetInvocationList())
watcher.Changed -= eventDelegate;
}
无论Changed事件是如何被引用,编译器会报告: 事件“System.IO.FileSystemWatcher.Changed”只能出现在左手侧+ =或 - =
上面的代码工作得很好,在同一类的事件工作时:
public event FileSystemEventHandler MyFileSystemEvent;
private void MethodName()
{
MyFileSystemEvent += new FileSystemEventHandler(watcher_Changed);
MyFileSystemEvent = null; // This works.
// This works, too.
foreach (FileSystemEventHandler eventDelegate in
MyFileSystemEvent.GetInvocationList())
watcher.Changed -= eventDelegate;
}
那么,我错过了什么?看来我应该能够对FileSystemWatcher事件做同样的事情。
http://msdn.microsoft.com/en-us/library/st6sy9xe.aspx – 2011-05-26 00:20:24