【问题标题】:C# .net, syntax for when calling a method how to pass in variable with method [duplicate]C# .net,调用方法时的语法如何使用方法传递变量[重复]
【发布时间】:2016-02-10 05:26:58
【问题描述】:

如果这是一个非常简单的修复,我深表歉意,因为我是 C# 新手。 下面是一个用于在 Windows 中监视文件夹的代码 sn-p:

FileSystemWatcher watcher = new FileSystemWatcher();
            watcher.Path = label1.Text;

            watcher.NotifyFilter = NotifyFilters.LastWrite |
                                   NotifyFilters.LastAccess |
                                   NotifyFilters.FileName |
                                   NotifyFilters.DirectoryName;
"
            watch.Filter = "*.*";

            watcher.Created += new FileSystemEventHandler(OnChanged(label4));
            watcher.EnableRaisingEvents = true;

如您所见,当我正在监视文件夹中“创建”的文件时,它会为每个文件执行 OnChanged 方法。

我的 .net 应用程序上有一个标签,我想将该标签文本作为字符串变量传递给 OnChanged 方法。 我的问题是如何将变量传递给 OnChanged 方法? 看来我尝试过的任何语法,包括上述语法 Visual Studio 2010 都不喜欢它。

onChanged 方法如下所示:

            public static void OnChanged(object source, FileSystemEventArgs e, String label4)
            {
                FileInfo file = new FileInfo(e.FullPath);
                String fileName = file.Name;
                String outputPath = label4.Text + file.Name;
            }

【问题讨论】:

标签: c# .net visual-studio-2010


【解决方案1】:

你不能直接传递你的参数,但你可以使用 lambda 表达式来包装它。

watcher.Created += (source, e) => OnChanged(source, e, label4);

【讨论】:

    【解决方案2】:

    您可以为此使用 lambda 表达式:

    watcher.Created += (sender, args) => OnChanged(label)
    

    Some background on lambda expressions

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-01
      • 2015-05-03
      • 1970-01-01
      • 2015-07-20
      • 2021-06-07
      • 2014-06-28
      相关资源
      最近更新 更多