调用带参数的事件处理程序 [英] call an eventhandler with arguments
本文介绍了调用带参数的事件处理程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
Visual Studio 2008中,C#3.0。
下面我有它调用的事件处理程序的方法。我想通过该方法的事件处理程序收到两个参数
我愿做这样的事情:
wc.DownloadDataCompleted + = wc.DownloadedDataCompleted(strtitle,placeid);
这甚至可能,如果是,我怎么会去这样做?
代码段:
公共无效downloadphoto(字符串struri,串strtitle,串placeid)
{使用
(Web客户端WC =新的WebClient())
{
wc.DownloadDataCompleted + = wc_DownloadDataCompleted;
wc.DownloadDataAsync(新的URI(struri));
}
}
解决方案
的要做到这一点最简单的方法是使用的匿名函数的(匿名方法或lambda表达式)认购事件,然后做出你的方法有你想要的参数:
公共无效downloadphoto(字符串struri,串strtitle,串placeid)使用
{
(Web客户端WC =新的WebClient())
{
wc.DownloadDataCompleted + =(发件人,参数)=>
DownloadDataCompleted(strtitle,placeid,参数);
wc.DownloadDataAsync(新的URI(struri));
}
}
//请重新命名要说它做什么,而不是它的使用在这里:)
私人无效DownloadDataCompleted(字符串名称,字符串ID的方法,
DownloadDataCompletedEventArgs参数)
{
//做的东西在这里
}
Visual Studio 2008, C# 3.0.
I have a method below which calls an event handler. I would like to pass the two arguments received by the method to the event handler.
I would like to do something like this:
wc.DownloadDataCompleted += wc.DownloadedDataCompleted(strtitle, placeid);
Is this even possible, if yes, how would I go about doing it ?
Code Snippet:
public void downloadphoto(string struri,string strtitle,string placeid)
{
using (WebClient wc = new WebClient())
{
wc.DownloadDataCompleted += wc_DownloadDataCompleted;
wc.DownloadDataAsync(new Uri(struri));
}
}
解决方案
The easiest way to do this is to use an anonymous function (an anonymous method or a lambda expression) to subscribe to the event, then make your method have just the parameters you want:
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
}
这篇关于调用带参数的事件处理程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文