使用委托时,有没有办法获取对象响应?

时间:2011-10-04 12:57:47

标签: c# delegates anonymous-methods

举个例子:

  

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

5 个答案:

答案 0 :(得分:3)

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

或者如果您喜欢委托语法

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

答案 1 :(得分:3)

如果你真的想使用匿名委托而不是lambda:

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

答案 2 :(得分:3)

您应该可以使用以下内容:

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

答案 3 :(得分:3)

其他答案使用lambda表达式,但为了完整性,请注意您还可以specify委托的参数:

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

答案 4 :(得分: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));
    }
}