用参数调用eventhandler

dez*_*kev 12 c# events handlers

Visual Studio 2008,C#3.0.

我有一个调用事件处理程序的方法.我想将方法​​接收的两个参数传递给事件处理程序.

我想做这样的事情:

wc.DownloadDataCompleted += wc.DownloadedDataCompleted(strtitle, placeid);
Run Code Online (Sandbox Code Playgroud)

这是否可能,如果是的话,我该怎么做呢?

代码片段:

public void downloadphoto(string struri,string strtitle,string placeid)
{
    using (WebClient wc = new WebClient())
    {
        wc.DownloadDataCompleted += wc_DownloadDataCompleted;
        wc.DownloadDataAsync(new Uri(struri));
    }
}
Run Code Online (Sandbox Code Playgroud)

Jon*_*eet 25

最简单的方法是使用匿名函数(匿名方法或lambda表达式)来订阅事件,然后让你的方法只有你想要的参数:

public void downloadphoto(string struri, string strtitle, string placeid)
{
    using (WebClient wc = new WebClient())
    {
        wc.DownloadDataCompleted += (sender, args) => 
            DownloadDataCompleted(strtitle, placeid, args);
        wc.DownloadDataAsync(new Uri(struri));
    }
}

// Please rename the method to say what it does rather than where it's used :)
private void DownloadDataCompleted(string title, string id, 
                                   DownloadDataCompletedEventArgs args)
{
    // Do stuff here
}
Run Code Online (Sandbox Code Playgroud)

  • 你如何取消订阅活动? (3认同)
  • @jdelator:您需要将委托存储在变量中并使用它来取消订阅. (2认同)

Rex*_*x M 5

DownloadDataAsync 有一个带对象的重载:

DownloadDataAsync(uri, object)
Run Code Online (Sandbox Code Playgroud)

该对象可以是您想要传递给的任意对象DownloadDataCompleted handler

public void downloadphoto(string struri,string strtitle,string placeid)
{
    using (WebClient wc = new WebClient())
    {
        string[] data = new string[2] { strtitle, placeid };
        wc.DownloadDataCompleted += wc_DownloadDataCompleted;
        wc.DownloadDataAsync(new Uri(struri), data);
    }
}


void wc_DownloadDataCompleted(object sender, DownloadDataCompletedEventArgs e)
{
    string[] data = (string[])e.UserToken;
    string strtitle = data[0];
    string placeid = data[1];
}
Run Code Online (Sandbox Code Playgroud)