c# - 使用参数调用事件处理程序

标签 c# events handlers

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));
    }
}

最佳答案

最简单的方法是使用匿名函数(匿名方法或 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
}

关于c# - 使用参数调用事件处理程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1488099/

相关文章:

events - 如何捕获 dijit.form.NumberSpinner 的递增和递减事件?

c# - WPF 创建一个控件列表,可以通过鼠标滚动但仍保持功能

python - 设置延迟参数时 RotatingFileHandler 抛出异常

c# - Java 中 C# 事件的替代

javascript 事件处理程序无法正常工作

go - 在 LoggingHandlers 中自定义日志格式 在 GO 中的 Gorilla 处理程序中实现

c# - hotmail无法连接到远程服务器

c# - 从字符串中删除所有 "invisible"个字符?

c# - 如何使用 C# 使用 MsTest 对属性进行单元测试?

c# - 正则表达式捕获括号内的值,值也包含括号