【问题标题】:When using a delegate, is there a way to get hold of the object response?使用委托时,有没有办法获取对象响应?
【发布时间】:2011-11-30 16:28:28
【问题描述】:
举个例子:
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?
【问题讨论】:
标签:
c#
delegates
anonymous-methods
【解决方案1】:
wc.DownloadStringCompleted +=
(s, e) => {
var result = e.Result;
};
或者如果你喜欢委托语法
wc.DownloadStringCompleted +=
delegate(object s, DownloadStringCompletedEventArgs e) {
var result = e.Result;
};
【解决方案2】:
如果你真的想使用匿名委托而不是 lambda:
wc.DownloadStringCompleted += delegate(object sender, DownloadStringCompletedEventArgs e)
{
// your code
}
【解决方案3】:
您应该能够使用以下内容:
using (WebClient wc = new WebClient())
{
wc.DownloadStringCompleted += (s, e) =>
{
string fileContent = (string)e.Result;
};
wc.DownloadStringAsync(new Uri(fileUrl));
}
【解决方案4】:
其他答案使用 lambda 表达式,但为了完整起见,请注意您也可以 specify 代表的参数:
wc.DownloadStringCompleted +=
delegate(object sender, DownloadStringCompletedEventArgs e) {
// Use e.Result here.
};
【解决方案5】:
试试这个:
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));
}
}