如何访问事件中的其他类

本文关键字:其他 事件 何访问 访问 | 更新日期: 2023-09-27 18:06:01

我试图访问在文件下载完成时触发的事件下面的代码块中的脚本类。我怎么能做到呢?

 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");
        }
    }

如何访问事件中的其他类

可以使用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) {
  ...
}