Additional parameters for FileSystemEventHandler

风流意气都作罢 提交于 2019-12-05 06:03:25
foreach (String config in configs)
{
    ...
    FileWatcher.Created += (s,e) => DoSomething(e.FullPath, mSettings);
    ...
}

foreach (String config in configs) 
{ 
    ... 
    MySettings mSettings = new MySettings(...); // create a new instance, don't modify an existing one
    var handler = new System.IO.FileSystemEventHandler( (s,e) => FileSystemWatcherCreated(s,e,msettings) );
    FileWatcher.Created += handler;
    // store handler somewhere, so you can later unsubscribe
    ... 
} 

void FileSystemWatcherCreated(object sender, System.IO.FileSystemEventArgs e, MySettings mSettings) 
{ 
    DoSomething(e.FullPath, mSettings); 
} 

You can't ask for more information than what the FileWatcher handler provides. What you can do however is to create a small classes that have access to the configuration and also have a delegate that you can attach to the FileWatcher's Created event

class Program
{
    static void Main(string[] args)
    {
        FileSystemWatcher watcher = new FileSystemWatcher("yourpath");

        var configurations = new IConfiguration[]
                                 {
                                     new IntConfiguration(20),
                                     new StringConfiguration("Something to print")
                                 };

        foreach(var config in configurations)
            watcher.Created += config.HandleCreation;
    }

    private interface IConfiguration
    {
        void HandleCreation(object sender, FileSystemEventArgs e);
    }

    private class IntConfiguration : IConfiguration
    {
        public IntConfiguration(int aSetting)
        {
            ASetting = aSetting;
        }

        private int ASetting { get; set; }

        public void HandleCreation(object sender, FileSystemEventArgs e)
        {
            Console.WriteLine("Consume your settings: {0}", ASetting);
        }
    }

     public class StringConfiguration : IConfiguration
    {
        public string AnotherSetting { get; set;}

        public StringConfiguration(string anotherSetting)
        {
            AnotherSetting = anotherSetting;
        }

        public void HandleCreation(object sender, FileSystemEventArgs e)
        {
            Console.WriteLine("Consume your string setting: {0}", AnotherSetting);
        }
    }
}

You need to understand what you are using. FileSystemEventHandler's definition is-

public delegate void FileSystemEventHandler(object sender, FileSystemEventArgs e);

You can't pass the third argument. In order to pass the data 'mSettings', you might have to write your own extra code, I'm afraid.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!