2017-04-03 85 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') ; 
    }