C# Pass a delegate as an argument
I am aware I can do this:
WebClient client = new WebClient(); client.UploadStringCompleted += delegate(object sender, UploadStringCompletedEventArgs e) { //handle even开发者_如何学Ct }; client.UploadStringAsync(myURI, "POST", "some_data");
But is there a way I can pass an inline delegate as an argument? Something like this:
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); }
Yes, that code is correct, except you can't call your parameter event. I'd also use a lambda expression instead because it's nicer.
DoRequest("some_data", (o, e) => {/* handle event */});
Yes, you can write exactly that except that event
is a keyword and can't be used as a variable name.
精彩评论