将事件处理程序的定义作为lambda表达式传递

时间:2017-04-03 23:21:31

标签: c# delegates event-handling

static void Main(string[] args)
{
        Watcher w = new Watcher();
        w.watch(@"someLocation", (() => { MoveFiles.Move() ; return 0; }));
}

public void watch(string pathName, Func< int> OnChanged)
{
            FileSystemWatcher watcher = new FileSystemWatcher();
            watcher.Path = pathName;
            watcher.Filter = "*.*";
            watcher.Created += new FileSystemEventHandler(OnChanged);
            watcher.EnableRaisingEvents = true;
            Console.WriteLine("Press \'q\' to quit the sample.");
            while (Console.Read() != 'q') ;
}

我试图将OnChanged事件的定义作为lambda表达式传递,但我得到了

  

错误:没有Func的重载匹配委托&#34; System.IO.FileSystemEventHandle&#34;

我尝试将代理Func<int>更改为Func<Object, FileSystemEventArgs, int>,但仍然出现错误。

请指教。

3 个答案:

答案 0 :(得分:2)

FileSystemEventHandler委托只有两个参数 - sender objectFileSystemEventArgs参数。并且它不会返回任何值。即它的签名如下:

public void FileSystemEventHandler(object sender, FileSystemEventArgs e)

Lambda应匹配此签名 - 它不应返回任何值,并且它应接受如上所述的两个参数。您可以使用FileSystemEventHandlerAction<object, FileSystemEventArgs>委托作为方法参数:

public void watch(string pathName, FileSystemEventHandler OnChanged)
{
   // ...
   watcher.Created += OnChanged;
}

将lambda传递给此方法:

w.watch(@"someLocation", (s,e) => MoveFiles.Move());

注意:FileSystemEventHandlerAction<object, FileSystemEventArgs>代表之间没有隐式转换。因此,如果您使用Action<object, FileSystemEventArgs>类型的处理程序,那么您应该以这种方式附加它:

watcher.Created += new FileSystemEventHandler(OnChanged);

答案 1 :(得分:0)

OnChanged应该有签名

private static void OnChanged(object source, FileSystemEventArgs e)
{

}

不是Func<int>

您应该传递Action<object, FileSystemEventArgs>而不是

请参阅its MSDN page

答案 2 :(得分:0)

试试这个:

static void Main(string[] args)
    {
        Watcher w = new Watcher();
        w.watch(@"someLocation", (source, e) => { MoveFiles.Move(); });
    }


    public void watch(string pathName, FileSystemEventHandler OnChanged)
    {
        FileSystemWatcher watcher = new FileSystemWatcher();
        watcher.Path = pathName;
        watcher.Filter = "*.*";
        watcher.Created += OnChanged;
        watcher.EnableRaisingEvents = true;
        Console.WriteLine("Press \'q\' to quit the sample.");
        while (Console.Read() != 'q') ;
    }