2011-10-04 62 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. 
    }; 
相关问题