views:

36

answers:

1

I have list of objects that contain information about which classes static EventHandler should be listen to whitch folder. I know this doesn't work but you'll get the idea..

(eventhandler doesn't have to be static, class can also be a singleton, but somehow I have to add an EventHandler based on the type specified)

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  A: 

Use Delegate.CreateDelegate(Type, MethodInfo):

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