What is extension methods )?

Source: Internet
Author: User
Tags valid email address

Link to the original English text:

Http://weblogs.asp.net/scottgu/archive/2007/03/13/new-orcas-language-feature-extension-methods.aspx

What is the extension method ):

The extension method allows developers to add new methods to an existing CLR type public contract (contract) without generating subclass or re-compiling the original type. The extension method helps to integrate the flexibility of duck typing support popular in today's dynamic languages with the performance of strong language and compile-time verification.

The extension method facilitates many useful use cases and makes it possible to introduce a very powerful LINQ query framework in the. NET version released as part of orcas.

Example of a simple extension method:

Have you ever wondered whether a string variable is a valid email address? Today, you probably need to check whether the string variable is valid by calling a separate class (or a static method. For example:

 

String email = request. querystring ["email"];

If (emailvalidator. isvalid (email )){

}

 

Using the new "Extension Method" language features in C # and VB, I can add a useful "isvalidemailaddress ()" method to the string class itself, this method returns whether the current string instance is a valid string. Then I can rewrite my code to make it clean and descriptive, like this:

 

String email = request. querystring ["email"];

If (email. isvalidemailaddress ()){

}

 

How do we add this new isvalidemailaddress () method to the existing string class? We implement this by defining a static type with our static method "isvalidemailaddress", as shown below:

 

Public static class scottguextensions
{
Public static bool isvalidemailaddress (this string S)
{
RegEx = new RegEx (@ "^ [\ W-\.] + @ ([\ W-] + \.) + [\ W-] {2, 4} $ ");
Return RegEx. ismatch (s );
}
}

 

Note that the above static method has a "This" keyword before the parameter variable of the first type is string, which tells the compiler, this specific extension method should be added to an object of the "string" type. Then, in the isvalidemailaddress () method implementation, I can access all the public attributes, methods, and events of the actual string instance that calls this method, returns true/false depending on whether it is a valid email address.

In my code, add the implementation of this specific extension method to the string instance. I only need to use the standard "using" statement to introduce the namespace containing the implementation of this extension method:

 

Using scottguextensions;

 

Then the compiler will correctly locate the isvalidemailaddress () method on any string. C # and VB in the open release of orcas in October March provide complete support for the Extension Method in the Visual Studio code editor. Therefore, when I click the "." keyword on a string variable, my extension method will now appear in the intelliisense drop-down box:

The VB and C # compilers will naturally give you a compile-time check on the usage of all extension methods, which means you will get a compile-time error, if you use an extension method with an incorrect or incorrect key.

[ThanksDavid Hayden,It was his last year'sAn old post The first example demonstrates the use of isvalidemailaddress..]

Extended Application scenarios continued...

The new extension method is used to add methods to individual types, which opens up many useful extension application scenarios for developers. But what makes the extension methods very powerful is that they can be applied not only to individual types, but also to any base class or interface in the. NET Framework. This allows developers to create a variety of framework layer extensions that can be used throughout the. NET Framework.

For example, in such a scenario, I want to check whether an object is included in an object set or array in an easy, descriptive, and strong way. I can define a simple. in (SET) extension method, I want to add it. on all objects in the. NET Framework, I can implement this "in ()" Extension Method in C:

Note how I declare the first parameter of the extension method above: "This object O ". This indicates that this extension method should apply to all types inherited from the base class system. object, which means that I can use it on every object in. net.

The implementation of the "in" method above allows me to check whether a specified object is contained in an ienumerable sequence passed in as a method parameter. Because all. net collections and arrays implement the ienumerable interface, now I have a useful and descriptive method to checkAnyWhether the object belongsAny. Net collection or array.

Then I can use this "in ()" method to check whether a specific string is in a string array:

I can also use it to check whether a specific ASP. Net control is in a container control set:

I can even use it on a scalar data type like an integer:

Note that you can even use the extension method on basic data type values such as integer 42. Because CLR supports automatic boxing/unboxing of the numerical type, the extension method can be directly used in the numerical value and other scalar data types.

You can probably see from the above example that the extension method can facilitate some very rich and descriptive scalability application scenarios. When used in. NET Common base classes and interfaces, they can facilitate some very good domain-specific frameworks and combined use scenarios.

Built-in system. LINQ Extension Method

A built-in extension Library released with. Net in orcas is a powerful query extension method that allows developers to query any data. These extension methods are implemented in the new system. the Extension Method of the standard query operator is defined under the namespace of LINQ.. NET developers can easily query XML and relational databases ,. net object, and any other data structure type. (So this is the linq ...)

The following are several benefits of the extended model using these query extension methods:

1) it allows a common query programming model and syntax for all data types (databases, XML files, objects in memory, and web-services.

2) It can be combined to allow developers to easily add new methods/operators to the query syntax. For example, we can use our custom "in ()" method with the standard "where ()" method defined for LINQ as part of a separate query. The custom in () method looks the same as the standard method provided by the system. LINQ namespace.

3) it is scalable and can be used with any data provider type. For example, any existing ORM engine such as nhibloud or llblgen can implement standard query operators of LINQ to allow their existing ORM implementation and LINQ ing engine to implement LINQ query. This allows developers to learn a common way to query data, and then use the same skills for a wide variety of data storage.

I will give you more examples of LINQ in the next few weeks, but I would like to give you a few examples. These examples show how to use several built-in extension methods for LINQ query for different types of data:

Scenario 1: Use the LINQ Extension Method for. Net objects in the memory

Suppose we define a class that represents "person" like this:

Then I can create and fill in a "people" set using the new object initiator and set initiator features, as shown in the following code:

Then I can use. the standard "where ()" extension method provided by LINQ to obtain the "person" objects whose first character of firstname in this set is "S", like this:

The new p => syntax above is an example of a "Lambda expression", which is a more concise development of support for C #2.0 anonymous methods, you can use a real parameter to easily express the query and filter (in this case, we indicate that we only want to return a string of person objects with the first character of the firstname attribute "S ). The above query then returns the sequence of two objects, Scott and Susanne.

You can also use. the new "average" and "MAX" extension methods provided by LINQ write code to determine the average age of people in my set, and the person with the largest age, like this:

Scenario 2: Use the LINQ Extension Method for XML files

It is rare for you to manually create a hard-coded data set in the memory. It is more likely that you will obtain data from an XM file, database, or web service.

Suppose we have an XML file on the hard disk that contains the following data:

Obviously, I can use the existing system. XML APIs loads the XML file into a Dom and then accesses it, or uses a lower-level xmlreader API for manual analysis. Alternatively, in Orcas, I can also use the system. xml. LINQ implementation (that is, xlinq) that supports the standard LINQ extension method to analyze and process XML more elegantly.

The following code example shows how to use LINQ to obtain the <person> XML element whose first letter contains the value of a subnode is "S:

Note that it uses the same where () extension method as the object in the memory. Now it returns an "xelement" element sequence. xelemen is an XML node element of no type. Alternatively, I can rewrite the query expression and construct the data shape using the select () Extension Method of LINQ, provide a Lambda expression that uses the new object initializer syntax to fill in the same "person" class, just like an example of the Set in our first memory:

The above code will open, analyze, and filter XML, and then return all the work of a strong person object sequence. No ing or persistent files are required to map values, I just pointed out the configuration from XML to the object in the above LINQ query.

I can also use the same average () and max () LINQ extension methods as before to calculate the average age and maximum age of the <person> element in the XML file, as shown in the following code:

I don't need to manually analyze XML files. xlinq can not only Process Analysis for me, but also use lower-layer xmlreader instead of Dom to analyze files when estimating the LINQ expression. This means that it is fast and does not allocate a lot of memory.

Scenario 3: Use the LINQ Extension Method for Databases

Assume that we have an SQL database containing a table named "people", which has the following data definitions:

I can quickly create a "person" class mapped to the database by using the wysiwyg orm designer of the new LINQ to SQL in Visual Studio:

Then, I can use the same LINQ where () extension method that I used previously for objects and XML files to obtain a sequence of strong type "person" objects whose first character is "S" from the database:

Note that the query syntax is exactly the same as that in the XML scenario.

Then, I can use the same extension methods as the previous method of LINQ average () and max () to obtain the average and maximum values from the database, as shown in the following code:

To make the preceding code example work, you do not need to write any SQL code yourself. The LINQ er of the LINQ ing between the LINQ and SQL objects provided in orcas processes the objects that are retrieved, tracked, and updated to your database data definitions and stored procedures. You only need to use any LINQ Extension Method to filter and configure the results. Then, the SQL code needed to obtain data is executed from the SQL statement (note, the above average and Max extension methods obviously do not return all data rows from the data table, they will use the tsql aggregate function to calculate the value in the database, returns only one scalar value ).

Watch a video I made in March to demonstrate how the data productivity in orcas has been significantly improved by using the SQL-to-SQL method. In the video, you can also see the real-world demonstration of the New ORM designer from LINQ to SQL, as well as the complete intelliisense provided by the Code Editor for the data model compiling of the data model.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.