使用参数调用事件处理程序
Visual Studio 2008,C# 3.0。
我有一个调用事件处理程序的方法。我想将该方法接收到的两个参数传递给事件处理程序。
我想做这样的事情:
wc.DownloadDataCompleted += wc.DownloadedDataCompleted(strtitle, placeid);
这是否可能,如果是,我将如何去做?
代码片段:
public void downloadphoto(string struri,string strtitle,string placeid)
{
using (WebClient wc = new WebClient())
{
wc.DownloadDataCompleted += wc_DownloadDataCompleted;
wc.DownloadDataAsync(new Uri(struri));
}
}
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));
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
DownloadDataAsync
有一个重载,它接受一个对象:该对象可以是您想要传递到
DownloadDataCompleted 处理程序
中的任意对象:DownloadDataAsync
has an overload which takes an object:That object can be any arbitrary thing you want that gets passed into the
DownloadDataCompleted handler
:您可以创建一个私有类并将处理程序放在那里。例如
,尽管如此,考虑到乔恩回答的优雅,可能会使用它!
You could create a private class and place the handler in there. E.g.
Although, given the elegance of Jon's answer would probably use that!
Jon Skeet 已经回答了这个问题,展示了如何使用 lamda 表达式,但我仍然不清楚。我仍然需要更多示例,并最终使用按钮找到了这个简单的案例: http://social.msdn.microsoft.com/Forums/en-US/csharpgeneral/thread/74d03fe0-0fa5-438d-80e0-cf54fa15af0e
在我的案例中,我使用了 TreeView 控件的上下文菜单,最终看起来像这样:
Jon Skeet already answered this, showing how to use a lamda expression, but I was still unclear about it. I still needed some more examples, and eventually found this simple case using a button: http://social.msdn.microsoft.com/Forums/en-US/csharpgeneral/thread/74d03fe0-0fa5-438d-80e0-cf54fa15af0e
In my case, I was using a context menu for a TreeView control, which ended up looking like this:
最简单的方法是使用匿名函数(匿名方法或 lambda 表达式)来订阅事件,然后让您的方法仅包含您想要的参数:
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: