首页 > 解决方案 > 带有文件系统观察程序的 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') ;
        }
    }
}

标签: c#.netlambdadelegates

解决方案


只是为了选择其中一个事件......

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。


推荐阅读