8

我正在尝试编写一个程序,该程序可以监视多个文件夹的文件创建并启动相同的操作,但每个文件夹的设置不同。我的问题是为 FileSystemEventHandler 指定一个额外的参数。我为每个目录创建一个新的 FileWatcher 来监视和添加 Created-action 的处理程序:

foreach (String config in configs)
{
    ...
    FileWatcher.Created += new System.IO.FileSystemEventHandler(FileSystemWatcherCreated)
    ...
}

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

如何将“mSettings”变量传递给 FileSystemWatcherCreated()?

4

4 回答 4

9

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); 
} 
于 2010-04-14T09:53:05.500 回答
6
foreach (String config in configs)
{
    ...
    FileWatcher.Created += (s,e) => DoSomething(e.FullPath, mSettings);
    ...
}
于 2010-04-14T09:41:25.190 回答
0

您不能要求比FileWatcher处理程序提供的更多信息。但是,您可以做的是创建一个可以访问配置的小类,并且还有一个可以附加到FileWatcher'Created事件的委托

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);
        }
    }
}
于 2010-04-14T09:37:07.023 回答
0

您需要了解您正在使用什么。FileSystemEventHandler的定义是——

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

你不能通过第三个参数。为了传递数据“mSettings”,恐怕您可能必须编写自己的额外代码。

于 2010-04-14T09:38:23.837 回答