LINQ experience (3) -- C #3.0 new language features and improvements (Part 2)

Source: Internet
Author: User
Tags valid email address

In the previous article, we introduced the features and improvements of the new C #3.0 language. In this article, we will continue to introduce the remaining parts.

C #3.0 new language features and improvements include:

    • Auto-implemented Properties)
    • Local variable type inference)
    • Anonymous type (anonymous types)
    • Object and collection initializers)
    • Extension methods)
    • Lambda expression and Lambda Expression Tree (lambda expression and Lambda expression trees)
Extension methods)

We often need to perform some operations on the CLR type, but we cannot extend the methods of the CLR type. We can only create some helper methods or inherit classes. Let's modify the above user class:

Public Class User
{
Public Int Id { Get ;Set ;}
Public String Name { Get ; Set ;}
Public Int Age { Get ; Set ;}
Public String Read ()
{
Return "ID :" + ID + "Name :" + Name + "Age :" + Age;
}
}

Then call

 
VaRUser =New{Id = 1, name ="Yjinglee", Age = 22 };VaRSTR = user. Read ();

Now the extension method is much more convenient.

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. --Reference Scott blog

The extension method is a static method that can be called by using the instance method syntax. In effect, it is possible to extend the existing type and construction type of the attached method. It can expand existing class functions so that instances of this type have more methods (functions ).
The extension method does not change.Source codeExtension (that is, adding can not be modified) in the existing type of instance method.

What is the idea of the extension method? Let's do it step by step!
First declare the extension method: Modify the first parameter of the method by specifying the keyword "this. Note that the extension method can only be declared in a static class. The extension method has all the capabilities of all conventional static methods and can be called using the instance method syntax. Then you can call the extension method. The following is an example:
For example, we want to check whether a string variable is a valid email address? In the. net2.0 framework, it is like this:

VaREmail =Leeyongjing@gmail.com";If(Emailvalidator. isvalid (email) {response. Write ("Yjinglee prompt: this is a correct email address");}

With the extension method, I can add the "isvalidemailaddress ()" method to the string class itself, which returns whether the current string instance is a legal string.

If(Email. isvalidemailaddress () {response. Write ("Yjinglee prompt: this is a correct email address");}

How do we add this isvalidemailaddress () method to the existing string class? First, define a static class, and then define the "isvalidemailaddress" static method.

 Public   Static   Class   Extensions  // Static class { Public   Static  Bool Isvalidemailaddress ( This   String S) // Static method and this { RegEx 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.

Extension methods can be applied to not only individual types, but also any base classes or interfaces in the. NET Framework. It can be used for the wide range of composite framework layer extensions of the entire. NET Framework.

Key points of the Extension Method
    1. The essence of an extension method is to change an instance method call to a static method call in a static class during the compilation period. In fact, it does have all the functions of static methods.
    2. The scope of the extension method is visible to the entire namespace. You can use using namespace to import extension methods from other namespaces.
    3. Extension Method priority: the existing instance method has the highest priority, followed by the static method of the static class under the nearest namespace, and finally the static method of the static class under the distant namespace.
    4. The extension method is a compilation technology. Pay attention to the differences with runtime technologies such as reflection and use them with caution.

 

Lambda expressions and Lambda Expression Tree (lambda expression andlambda expression trees) Lambda expressions

Let's start with "finding all strings that contain yjinglee substrings. In C #2.0, the anonymous method allows us to delegate instances in an in-memory manner. It provides a powerful functional method.Programming LanguageBut the mark is quite lengthy and mandatory. We use the anonymous method in C #2.0 to search,CodeAs follows:

VaRInstring = List. findall (Delegate(StringS ){ReturnS. indexof ("Yjinglee")> = 0 ;});

Now we can use the lambda expression that comes with C #3.0 to allow us to achieve the same effect similar to the anonymous method in a way that is closer to human thinking and more natural, let's see how simple the following code is:

VaRInstring = List. findall (S => S. indexof ("Yjinglee")> = 0 );

Lambda expression format: (parameter list) => expression or statement Block
Significance: Define the lambda acceptance parameter list, run the expression or statement block to return the value of the expression or statement block to this parameter list.

The Lambda expression parameter type can be implicit or explicit. In the explicit list, the type of each parameter is explicitly specified. In the implicit list, the type of the parameter is automatically inferred from the context of the lambda expression.
The parameter list of a Lambda expression can contain one or more parameters, or has no parameters. In a Lambda expression with a single hidden parameter, parentheses can be omitted from the parameter list.
For example:

 (x, y) => X * Y;  // multiple parameters, implicit type => Expression  X => X * 10;  // single parameter, implicit type => Expression  X =>{  return  X * 10 ;};  // single parameter, implicit type => statement block  ( int  X) => X * 10;  // single parameter, explicit type => Expression  ( int  X) = >{  return  X * 10 ;};  // single parameter, explicit type => statement block  () =>  console . writeline ();  // No parameter  

The following is an example:
In the previous post, we wrote a user class and added two people. Next, we use the new where and average methods provided by LINQ to return a subset of people in the set, and calculate the average age of people in this set:

 List < User > User = New   List < User > { New   User {Id = 1, name = "Yjinglee" , Age = 22 }, New   User {Id = 2, name = "Xieqing" , Age = 25 },}; VaR Results = user. Where (P => P. Name = "Yjinglee" ). Tolist (); // Obtain the filtering conditions used by a specific person. The p Parameter belongs to the user type.  VaR Average = user. Average (P => P. Age ); // Calculate the average age using the age value of the user object 

As follows:

Perform a brief analysis on this Lambda expression:

VaRResultsdelegate = user. Where (Delegate(User p ){ReturnP. Name ="Yjinglee";// Returns a Boolean value.});VaRAveragedelegate = user. Average (Delegate(User p ){ReturnP. Age ;});

Lambda expression l can be converted to delegate type D, which must meet the following conditions:
The parameter type of l must be the same as the number of parameters of D. The return type must be the same, whether it is an expression or a statement block. Note that implicit types must be involved in type discrimination.

Lambda Expression Tree

The Lambda Expression Tree allows us to process lambda expressions like processing data (such as reading and modifying. Here is an example:

Expression < Func < Int , Bool > Filter = n => (N * 3) <5; Binaryexpression Lt = ( Binaryexpression ) Filter. Body; Binaryexpression Mult = ( Binaryexpression ) Lt. Left; Parameterexpression En = ( Parameterexpression ) Mult. Left; Constantexpression Three = (Constantexpression ) Mult. Right; Constantexpression Five = ( Constantexpression ) Lt. Right; var Ne = filter. Compile (); Console . Writeline ( "Result: {0}, {1 }" , One (5), one (1 )); Console . Writeline ( "({0} ({1} {2} {3}) {4 })" , LT. nodetype, mult. nodetype, en. Name, three. Value, five. value );

As follows:


Key points of the lambda expression and Lambda Expression Tree

    1. The parameter types of lambda expressions can be ignored because they can be inferred based on the context.
    2. The body of a Lambda expression can be an expression or a statement block.
    3. The input parameters of lambda expressions are involved in type inference and method overload analysis.
    4. Lambda expressions and expression bodies can be converted into expression trees.
    5. The Expression Tree allows lambda expressions to represent data structures instead of code execution.

Now, I will briefly introduce the new language features and improvements of C #3.0 here. Next, I will officially enter the topic section of this series, "LINQ. In order to let everyone know, I write it in another way, and analyze a piece of LINQ statement to penetrate through the knowledge points of LINQ. Together, we can experience the fun of using LINQ. Stay tuned from: Li yongjing

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.