简体   繁体   English

如何将变量传递给C#中的事件?

[英]How do I pass a variable to an event in C#?

I am using FileSystemWatcher On the Changed Event, I want to pass an integer variable. 我正在使用FileSystemWatcher在Changed Event上,我想传递一个整数变量。

eg 例如

int count = someValue;
 FileSystemWatcher watcher = new FileSystemWatcher();
watcher.Path = "C:\temp";
watcher.Changed += new FileSystemEventHandler(fileSystemWatcher_Changed);

on the fileSystemWatcher_Changed, I want to take the count value and then do some work. 在fileSystemWatcher_Changed上,我想取计数值,然后做一些工作。 But how do I get that value. 但是我如何获得这个价值。

if I make count a global variable, it wouldn't be valid because count changes with each file changed event and it is passed from user. 如果我计算一个全局变量,它将无效,因为计数随每个文件的变化而改变了事件并且从用户传递。

The simplest approach is to use a lambda expression: 最简单的方法是使用lambda表达式:

watcher.Changed += (sender, args) => HandleWatcherChanged(count);

It sounds like you may want to pass count by reference though, if the method wants to update the value. 听起来你可能想要通过引用传递count ,如果方法想要更新值。

为什么不将FileSystemWatcher子类化并将计数传递给子类的构造函数?

You could maintain a global dictionary mapping each file (path) to its count: 您可以维护一个全局字典,将每个文件(路径)映射到其计数:

readonly Dictionary<string, int> filesChangeCount= 
    new Dictionary<string, int>();

Then, in your event handler, just increment the appropriate count in the dictionary: 然后,在事件处理程序中,只需增加字典中的相应计数:

void fileSystemWatcher_Changed(object sender, FileSystemEventArgs e)
{
    lock (filesChangeCount)
    {
        int count;
        filesChangeCount.TryGetValue(e.FullPath, out count);
        filesChangeCount[e.FullPath] = count++;
    }
}

If you want to know how often fileSystemWatcher_Changed was called globally, you could use a static variable as well. 如果您想知道全局调用fileSystemWatcher_Changed ,您也可以使用静态变量。 If you want to know the number of calls in one specific instance of the class, drop the static keyword. 如果您想知道该类的一个特定实例中的调用次数,请删除static关键字。

private static int _count;

private void fileSystemWatcher_Changed(object sender, EventArgs e)
{
    Console.WriteLine("fileSystemWatcher_Changed was called {0} times",
                      ++_count);
}

Just be aware that if you are using a global variable in your changed handler you should surround any use of your variable with a lock since your changed event will be called by more than one thread. 请注意,如果您在更改的处理程序中使用全局变量,则应该使用锁来包含对变量的任何使用,因为更改的事件将由多个线程调用。

private static int _count;
private object lockerObject = new object();
private void fileSystemWatcher_Changed(object sender, EventArgs e)
{
    lock(lockerObject)
    {
        Console.WriteLine("fileSystemWatcher_Changed was called {0} times",
                  ++_count);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM