如何访问事件中的其他类

时间:2011-08-17 21:51:03

标签: c# .net

我正在尝试在文件下载完成时触发的事件中访问下面代码块中的Script类。我怎么能这样做?

 public void DownloadScript(Script script, string DownloadLocation)
    {


        AddLog(GenerateLog("Downloading Script", "Started", "Downloading " + script.Name + " from " + script.DownloadURL + "."));
        WebClient Client = new WebClient();
        Client.DownloadFileCompleted += new System.ComponentModel.AsyncCompletedEventHandler(Client_DownloadFileCompleted);
        Client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(Client_DownloadProgressChanged);
        Client.DownloadFileAsync(new Uri(script.DownloadURL), DownloadLocation + "test1.zip");

    }

以下是触发的事件。

public void Client_DownloadFileCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e)
    {

        if (e.Error.Message != string.Empty)
        {
            AddLog(GenerateLog("Downloading Script", "Error", "There was an error downloading " + script.Name + " from " + script.DownloadURL + ". " + e.Error.Message));
            Console.WriteLine("Error");

        }
        else
        {
            AddLog(GenerateLog("Downloading Script", "Done", "Finished downloading " + script.Name + " from " + script.DownloadURL + "."));
            Console.WriteLine("Done");
        }

    }

1 个答案:

答案 0 :(得分:2)

您可以使用lambda表达式捕获Script对象,并将其作为额外参数传递给处理程序。

public void DownloadScript(Script script, string DownloadLocation) {
  ...
  WebClient Client = new WebClient();
  Client.DownloadFileCompleted += (sender, e) => Client_DownloadFileCompleted(
    sender, 
    e, 
    script);
}

public void Client_DownloadFileCompleted(
  object sender, 
  AsyncCompletedEventArgs e,
  Script script) {
  ...
}