2017-04-03 82 views
1
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表达式,但我得到传递事件处理程序的定义lambda表达式

Error: No Overload for Func matches the delegate "System.IO.FileSystemEventHandle"

我试图改变委托Func<int>Func<Object, FileSystemEventArgs, int>但仍获得一些错误。

请指教。

回答

2

FileSystemEventHandler代表恰好有两个参数 - 发送者objectFileSystemEventArgs一rgument。它不会返回任何价值。即它的签名如下所示:

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

谢谢you.It工作。 –

0

OnChanged应该有签名

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

} 

Func<int>

你应该传递一个Action<object, FileSystemEventArgs>代替

its MSDN page

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') ; 
    }