从另一个方法访问变量

时间:2014-05-06 20:06:44

标签: c# .net filesystemwatcher

编辑:问题已解决,请参阅下面的答案。

我无法从其他方法访问FileSystemWatcher

编辑:根据要求提供更多代码。

    public static void watch(string path)
    {
        FileSystemWatcher watcher = new FileSystemWatcher();

        watcher.Path = path;
        watcher.NotifyFilter = NotifyFilters.Attributes |
                       NotifyFilters.CreationTime |
                       NotifyFilters.DirectoryName |
                       NotifyFilters.FileName |
                       NotifyFilters.LastAccess |
                       NotifyFilters.LastWrite |
                       NotifyFilters.Security |
                       NotifyFilters.Size;
        watcher.Filter = "*.*";
        watcher.IncludeSubdirectories = true;
        watcher.Changed += new FileSystemEventHandler(OnChanged);
        watcher.Created += new FileSystemEventHandler(OnChanged);
        watcher.Deleted += new FileSystemEventHandler(OnChanged);
        watcher.Renamed += new RenamedEventHandler(OnChanged);
        watcher.EnableRaisingEvents = true;
    }

    private static void OnChanged(object sender, FileSystemEventArgs e)
    {
        // The reason for having this try block (and EnableRaisingEvents toggling) is to solve a known problem with FileSystemWatcher, in which the event is fired twice.

        try
        {
            MessageBox.Show("File changed.");

            watcher.EnableRaisingEvents = false; // Error: The name 'watcher' does not exist in the current context
        }
        finally
        {
            watcher.EnableRaisingEvents = true; //Error: The name 'watcher' does not exist in the current context
        }
    }

我想更改EnableRaisingEvents属性。

由于范围问题,我无法做到这一点。通常我要做的是在范围更大的地方声明FileSystemWatcher,但我不能在这里做,因为每次运行方法时都必须创建一个新的。

那么,如何从不同的方法更改对象的属性?

PS:我已经搜索过,并尝试了不同的东西,但最终没有任何效果。

编辑:只是为了澄清,我必须将FileSystemWatcher声明保留在方法中(而不是给它一个更大的范围,从而允许它被另一种方法修改)。这样做的原因是每次运行方法时我都需要创建一个新的。

1 个答案:

答案 0 :(得分:2)

在正常的.NET事件中,有一个名为sender的参数,其中包含发送事件的对象。如果您知道事件只有一种发件人类型,则可以将其强制转换为您的类型:

private static void OnChanged(object sender, FileSystemEventArgs e)
{
    var watcher = sender as FileSystemWatcher;

    try
    {
        MessageBox.Show("File changed.");

        watcher.EnableRaisingEvents = false; // Error: The name 'watcher' does not exist in the current context
    }
    finally
    {
        watcher.EnableRaisingEvents = true; //Error: The name 'watcher' does not exist in the current context
    }
}
相关问题