2011-08-17 34 views
1

我正試圖訪問在文件下載完成時觸發的事件中的代碼塊中的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"); 
     } 

    } 

回答

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) { 
    ... 
} 
+0

謝謝!這正是我需要這個工作。我一直在尋找答案。 – MattAitchison