2010-08-25 46 views
0

我有對象列表,其中包含靜態EventHandler應偵聽哪個類的信息文件夾。我知道這是行不通的,但你會得到這個想法..根據類型添加EventHandler

(事件處理程序不一定是靜態的,類也可以是一個單身人士,但不知何故我必須添加一個基於指定類型的EventHandler )

foreach (Service s in InitialParams.Services) 
{ 
    FileSystemWatcher w = new FileSystemWatcher(s.WatchFolder); 
    w.Created += new FileSystemEventHandler(s.Type.GetMethod("FileAdded")); //This doesn't work 
    w.EnableRaisingEvents = true; 
    watchers.Add(w); 
} 

回答

3

使用Delegate.CreateDelegate(Type, MethodInfo)

MethodInfo method = s.Type.GetMethod("FileAdded"); 
var handler = (FileSystemEventHandler) Delegate.CreateDelegate 
    (typeof(FileSystemEventHandler), method); 
w.Created += handler;