C#传递一个委托作为参数

时间:2010-12-22 22:30:24

标签: c# visual-studio-2008 visual-studio-2010 events arguments

我知道我可以这样做:

WebClient client = new WebClient();
client.UploadStringCompleted += delegate(object sender, UploadStringCompletedEventArgs e)
{
    //handle event
};
client.UploadStringAsync(myURI, "POST", "some_data");

但是有没有办法可以将内联委托作为参数传递?像这样:

DoRequest("some_data",
    delegate(object sender, UploadStringCompletedEventArgs e)
    {
        //handle event
    });

public void DoRequest(string data, UploadStringCompletedEventHandler event)
{
    WebClient client = new WebClient();
    client.UploadStringCompleted += event;
    client.UploadStringAsync(myURI, "POST", data);
}

2 个答案:

答案 0 :(得分:3)

是的,该代码是正确的,除非您无法调用参数事件。我也会使用lambda表达式,因为它更好。

DoRequest(“some_data”,(o,e)=> {/ *处理事件* /});

答案 1 :(得分:2)

是的,除了event是关键字且不能用作变量名之外,您可以完全写出来。