2011-10-04 37 views
4

舉個例子:使用委託時,是否有辦法獲取對象響應?

WebClient.DownloadStringAsync Method (Uri)

普通代碼:

private void wcDownloadStringCompleted( 
    object sender, DownloadStringCompletedEventArgs e) 
{ 
    // The result is in e.Result 
    string fileContent = (string)e.Result; 
} 

public void GetFile(string fileUrl) 
{ 
    using (WebClient wc = new WebClient()) 
    { 
     wc.DownloadStringCompleted += 
      new DownloadStringCompletedEventHandler(wcDownloadStringCompleted); 
     wc.DownloadStringAsync(new Uri(fileUrl)); 
    } 
} 

但是如果我們用一個匿名delegate,如:

public void GetFile(string fileUrl) 
{ 
    using (WebClient wc = new WebClient()) 
    { 
     wc.DownloadStringCompleted += 
      delegate { 
       // How do I get the hold of e.Result here? 
      }; 
     wc.DownloadStringAsync(new Uri(fileUrl)); 
    } 
} 

如何獲得持有e.Result那裏?

回答

3
wc.DownloadStringCompleted += 
      (s, e) => { 
       var result = e.Result; 
      }; 

,或者如果你喜歡的委託語法

wc.DownloadStringCompleted += 
      delegate(object s, DownloadStringCompletedEventArgs e) { 
       var result = e.Result; 
      }; 
3

如果你真的想使用匿名委託,而不是拉姆達:

wc.DownloadStringCompleted += delegate(object sender, DownloadStringCompletedEventArgs e) 
{ 
    // your code 
} 
2

試試這個:

public void GetFile(string fileUrl) 
{ 
    using (WebClient wc = new WebClient()) 
    { 
     wc.DownloadStringCompleted += 
      (s, e) => { 
       // Now you have access to `e.Result` here. 
      }; 
     wc.DownloadStringAsync(new Uri(fileUrl)); 
    } 
} 
3

你應該可以使用followi NG:

using (WebClient wc = new WebClient()) 
{ 
    wc.DownloadStringCompleted += (s, e) => 
     { 
      string fileContent = (string)e.Result; 
     }; 
    wc.DownloadStringAsync(new Uri(fileUrl)); 
} 
3

其他的答案使用lambda表達式,但爲了完整性,注意,你也可以specify委託的參數:

wc.DownloadStringCompleted += 
    delegate(object sender, DownloadStringCompletedEventArgs e) { 
     // Use e.Result here. 
    }; 
相關問題