.NET Anonymous Methods in C#
|
源代码网整理以下Anonymous Methods 源代码网整理以下Download code for this article here. public MainForm() { InitializeComponent(); Application.ApplicationExit += new EventHandler(Application_ApplicationExit); } public void Application_ApplicationExit(object sender, EventArgs args) { // Do something before the application closes. } 源代码网整理以下The same code can be written as an in-line, anonymous method: public MainForm() { InitializeComponent(); Application.ApplicationExit += delegate(object sender, EventArgs args) { // Do something before the application closes. }; } 源代码网整理以下As you can see, the syntax in the second part of the example saves us from having to define a separate, stand-alone method. This is the most obvious benefit of anonymous methods, but aside from aesthetics, it offers little real benefit to a developer. Now we will take a look at a more practical example that demonstrates what I consider to be a more important benefit of anonymous methods. One of the most useful implementations of this new language feature can be seen in some of the generic collection types, including the new List<T> class. List<T> is decorated with several static methods such as Exists, Find, FindAll, Remove, and RemoveAll, all of which accept a Predicate delegate (Predicate is generic delegate that has bool as its return type). public List<ContactInfo> SearchContacts(List<ContactInfo> fullList, string lastName) { return fullList.FindAll ( new Predicate<ContactInfo>(FindContact) ); } public bool FindContact(ContactInfo contact) { // No way to match last name on passed in contact info... } 源代码网整理以下 public List<ContactInfo> SearchContacts(List<ContactInfo> fullList, string lastName) { return fullList.FindAll ( delegate(ContactInfo contact) { return contact.LastName == lastName; } ); } 源代码网整理以下Notice two things: first, we no longer need to define a separate method for our callback operation since we are using an in-line, anonymous method; second, inside our anonymous method, we can directly reference the lastName variable, which is scoped outside our anonymous method, to compare to the LastName property of the ContactInfo instance passed in by the List<T>.FindAll method. Again, like the FindContact method in the original version, our anonymous method is called for every ContactInfo in the list. 源代码网整理以下The other day, I was asked by a friend to write a simple Windows Forms application that would take a list of URLs and retrieve basic headers for each, displaying the information in a DataGridView on a Form. After writing the code, I showed it to Peter and he suggested I make an article out of it....so here I am, writing this article and finally getting to the application that started the whole idea: The Web Resource Information Reader. T-W-R-I-R....TWRIR. I know, I know...pretty cool name :) 源代码网整理以下So anyway, back to the matter at hand. The design goal of this application was simple: Download headers from the various urls as quickly and efficiently as possible and display them back to the user. Well, when dealing with web resources, one is often at the mercy of the remote server and how efficiently it can serve our request. In this case, that could mean the user has to wait a long time to see results if say, 1 out of 6 URLs takes a long time to load. This type of scenario is always perfect for a multi-threaded solution. So for TWRIR, I use the .NET ThreadPool to run each of the URL requests. To implement this, I created a static class called Reader with a static method called GetResourcesInfo which returns a DataTable containing the length, last modified, server, and status code headers for each URL. The method takes an array of urls and a second bool parameter to indicate if we should also download the page content. For this example, I will present the entire method"s code first and breakdown its pieces below: (NOTE: I have highlighted the beginning and end lines of the anonymous method in green and the key lines of code to be discussed later in yellow) 软件开发网 www.mscto.com
public static DataTable GetResourcesInfo(string[] urls, bool includeContent) { // Create DataTable for results. DataTable table = new DataTable(); DataColumn contentColumn = new DataColumn("Content", typeof(string)); DataColumn urlColumn = new DataColumn("URL", typeof(string)); DataColumn serverColumn = new DataColumn("Server", typeof(string)); DataColumn dateLastModifiedColumn = new DataColumn("DateLastModified", typeof(string)); DataColumn lengthColumn = new DataColumn("Length", typeof(long)); DataColumn statusCodeColumn = new 源代码网推荐 源代码网供稿. |
