FileSystemWatcher 怎么传参数到委托中?foreach (KeyValuePairint, Pictures list in pictureList)//遍
FileSystemWatcher 怎么传参数到委托中?
foreach (KeyValuePair<int, Pictures> list in pictureList)//遍历字典生成图片
{
if (GenTecPic(list.Value.datapath, list.Value.macropath, 0))
{
FileSystemWatcher watcher = new FileSystemWatcher();//设置监视器
watcher.Path = list.Value.datapath;
watcher.Changed += new FileSystemEventHandler(TecDat_Changed);
watcher.Created += new FileSystemEventHandler(TecDat_Changed);
watcher.EnableRaisingEvents = true;
list.Value.watcher = watcher;
}
}
timer_tecplot.Enabled = true;
委托:
void TecDat_Changed(object sender, FileSystemEventArgs e)
{
}
字典里有几个我就会建几个监视器,在TecDat_Changed中我需要得到别的参数来生成我的图片。
现在有2种想法,不知道哪个可以实现?
1.我想知道是哪个watcher,这样就可以在字典中根据watcher来找到其他数据了;
2.在上面中我想把list.Value.macropath作为参数能传给委托。
急啊!!
[解决办法]最原始的(在.net1.1就支持的)是可以创建一个调用类型,例如
public class MytecProxy
{
public string path;
......以及其它任何必要的参数
public void TecDat_Changed(object sender, FileSystemEventArgs e)
{
//在这里,你就可以访问到所有参数
}
}
然后调用时写
MyTecProxy obj = new MyTecProxy();
obj.path = list.Value.macropath;
watcher.Changed += new FileSystemEventHandler(obj.TecDat_Changed);
这样,当事件处理方法执行时,你通过 obj.xxxx 赋值的参数全都可以取到。
在c#3.0中(好像是这个版本)出现了非常优雅的“匿名委托”写法,其中可以引用方法之前定义的变量。这就不用你自己去定义 MyTecProxy 类型了。你可以直接写[code=csharp]watcher.Changed += (s,e) =>
{
这里直接写事件处理代码,可以直接调用 list.Value.macropath!
}code]
因为匿名委托,会自动创建类似于 MyTecProxy 的内部类型,会自动将委托方法中使用到的外部变量编译为这个注册方法的过程的一部分。
匿名委托非常优雅!
[解决办法]事件处理中的sender就是FileSystemWatcher,你可以重写一个继承自FileSystemWatcher的类,添加一些属性保存你需要的信息,在事件中根据sender获取到Watcher,根据相应的属性就可以得到
[解决办法]sender意思就是谁触发了这个事件,你可以看.net framework源码,在invork的时候,传递的是this,也就是他自己。