c# - 带有文件系统观察程序的 Lambda 表达式
问题描述
我一生都无法弄清楚以下代码中这两个参数的来源。我已经在 Visual Studio 中编译了它,它可以工作,但是当您使用 lambda 表达式将匿名方法添加到 FileSystemWatcher 的委托时,这些方法如何接收这两个参数?他们来自哪里?当 .Changed 或 .OnChanged 事件发生时,FileSystemWatcher 是否返回带有两个参数的数组?如果是这样,我无法找到解释这一点的文档。这是代码:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MyDirectoryWatcher
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("***** The File Watcher App *****\n");
// Establish the path to the directory to watch.
FileSystemWatcher watcher = new FileSystemWatcher();
try
{
watcher.Path = @"C:\MyFolder";
}
catch (ArgumentException ex)
{
Console.WriteLine(ex.Message);
Console.WriteLine("Press Enter to continue...");
Console.ReadLine();
return;
}
// Set up the things to be on the lookout for.
watcher.NotifyFilter = NotifyFilters.LastAccess
| NotifyFilters.LastWrite
| NotifyFilters.FileName
| NotifyFilters.DirectoryName;
// Only watch text files.
watcher.Filter = "*.txt";
// Specify what is done when a file is changed, created, or deleted.
watcher.Changed += (s, e) =>
{
Console.WriteLine("File: {0} {1}!", e.FullPath, e.ChangeType);
};
watcher.Created += (s, e) =>
{
Console.WriteLine("File: {0} {1}!", e.FullPath, e.ChangeType);
};
watcher.Deleted += (s, e) =>
{
Console.WriteLine("File: {0} {1}!", e.FullPath, e.ChangeType);
};
watcher.Renamed += (s, e) =>
{
// Specify what is done when a file is renamed.
Console.WriteLine("File: {0} renamed to {1}", e.OldFullPath, e.FullPath);
};
// Begin watching the directory.
watcher.EnableRaisingEvents = true;
// Wait for the user to quit the program.
Console.WriteLine(@"Press 'q' to quit app.");
while (Console.Read() != 'q') ;
}
}
}
解决方案
只是为了选择其中一个事件......
watcher.Changed += OnChanged;
private void OnChanged(object sender, FileSystemEventArgs e){
// Handle event
}
每次执行 += 时,您实际上是在向 Changed 事件的调用列表添加一个委托。在这种情况下,委托定义了一个签名,该签名需要两个类型为 object 和 FileSystemEventArgs 的参数。
您可以使用 lambdas 对其进行简写: watcher.Changed += (sender, args) => {};
您需要查看事件的文档来计算签名(或使用像 Visual Studio 这样的 IDE): https ://docs.microsoft.com/en-us/dotnet/api/system.io.filesystemwatcher.changed
当 File System Watcher 需要调用事件(通知消费者发生了某些事情)时,它将调用事件调用列表中的所有委托,并传递发送者和 FileSystemEventArgs。
推荐阅读
- ruby-on-rails - 将 Rails 连接到 AWS MySQL 数据库
- entity-framework - 无法删除实体框架中的循环依赖对象
- matlab - 灰度直方图的同质性标准
- javascript - 如何使用javascript更改悬停时的图像源,但适用于每张照片
- android - Android中的角角
- python - 将字符串转换为操作
- python - python3中导入的变化
- google-app-engine - 应用引擎坚持绑定80端口
- javascript - 如何查看附加到 ios WkWebW HybridWebView 实现的 Safari 调试器的 console.log 输出?
- reactjs - 获取值异步函数javascript