变量和事件问题的范围 [英] scope of variables and events problem
本文介绍了变量和事件问题的范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在这里使用FileSystemWatcher,并且我希望保留在应用程序会话期间创建的所有文件的数组列表.
因此,在文件系统上发生事件之后,我想将文件添加到数组中.
现在,这不起作用.但是如何正确实施它.
片段
I am working here with FileSystemWatcher, and i want to keep an arraylist of all the files created during the session of the application.
So after and event on the filesystem i want to add the file to the array.
Now this doesn''t work. But how to implement it the right way.
snippit
class Import
{
private ArrayList a;
private FileSystemWatcher f;
public Import()
{
// create and configure Arraylist and FileWatcher here
f.Changed += new FileSystemEventHandler(OnChanged);
}
private static void OnChanged(object source, FileSystemEventArgs args)
{
// Here i cannot access the Arraylist a to add the args. to it.
}
}
对不起,新手级别
Sorry for the newbie level
推荐答案
添加到John的答案中:
该代码中的两个问题(尽管这可能不是您的实际代码)
1.您没有在任何地方实例化FileSystemWatcher
.
2.将OnChanged
设为非static
方法,它将可以访问a
成员.
意见建议:
1.将a
设置为List<>
而不是ArrayList
.
2.将a
重命名为更有意义的名称.
Adding to John''s answer:
Two problems in that code (although this may not be your actual code)
1. You are not instantiating yourFileSystemWatcher
anywhere.
2. MakeOnChanged
a non-static
method and it will be able to access thea
member.
Suggestions:
1. Makea
aList<>
instead of anArrayList
.
2. Renamea
to something more meaningful.
您可能想看看我的两部分文章系列.它不会完全回答您的问题,但它应该提供启发和使用FileSystemWatcher
对象的更好方法:
FileSystemWatcher-纯混沌(第1部分,共2部分) [ FileSystemWatcher-纯粹的混乱(第2部分,共2部分) [
You might want to check out my two-part article series. It won''t precisely answer your question, but it should provide enlightenment and a better way to use theFileSystemWatcher
object:
FileSystemWatcher - Pure Chaos (Part 1 of 2)[^]
FileSystemWatcher - Pure Chaos (Part 2 of 2)[^]
因为您的方法是static
如果您想通过该方法使用成员,也可以使其成为static
.
Since your method isstatic
you have to make your membersstatic
as well if you want to use them from that method.
static private ArrayList a;
这篇关于变量和事件问题的范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文