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 没有重载与委托"System.IO.文件系统事件句柄"匹配
我尝试将委托Func<int>
更改为Func<Object, FileSystemEventArgs, int>
但仍然遇到一些错误。
请指教。
FileSystemEventHandler
委托恰好有两个参数 - sender object
和 FileSystemEventArgs
参数。它不返回任何值。即它的签名看起来像:
public void FileSystemEventHandler(object sender, FileSystemEventArgs e)
Lambda 应与此签名匹配 - 它不应返回任何值,并且应接受上述两个参数。您可以使用FileSystemEventHandler
或Action<object, FileSystemEventArgs>
委托作为方法参数:
public void watch(string pathName, FileSystemEventHandler OnChanged)
{
// ...
watcher.Created += OnChanged;
}
将 lambda 传递给此方法:
w.watch(@"someLocation", (s,e) => MoveFiles.Move());
注意:FileSystemEventHandler
和Action<object, FileSystemEventArgs>
委托之间没有隐式转换。因此,如果您要使用Action<object, FileSystemEventArgs>
类型的处理程序,则应以这种方式附加它:
watcher.Created += new FileSystemEventHandler(OnChanged);
OnChanged
应该有签名
private static void OnChanged(object source, FileSystemEventArgs e)
{
}
不Func<int>
您应该改为传递Action<object, FileSystemEventArgs>
请参阅其 MSDN 页面
试试这个:
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') ;
}