Document directory
- Key points of the Extension Method
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
var user = new { Id = 1, Name = "YJingLee", Age = 22 };var str = 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 allows us to expand the existing instance methods without changing the source code (that is, adding and not modifying.
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:
VaR email = "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 = 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
- 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.
- The scope of the extension method is visible to the entire namespace. You can use using namespace to import extension methods from other namespaces.
- 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.
- 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 and Lambda 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 implement delegated instances in an in-memory manner. It provides a powerful functional programming language, but the markup is quite lengthy and mandatory. We use the anonymous method in C #2.0 for search. The Code is as follows:
var inString = list.FindAll(delegate(string s){ return s.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:
var inString = 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},}; // filter condition used to obtain a specific person. The p Parameter belongs to the user type var Results = user. where (P => P. name = "yjinglee "). tolist (); // use the age value of the user object to calculate the average age var average = user. average (P => P. age );
As follows:
Perform a brief analysis on this Lambda expression:
VaR resultsdelegate = user. where (delegate (User p) {return p. name = "yjinglee"; // return a Boolean value}); var averagedelegate = user. average (delegate (User p) {return p. 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 One = 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
- The parameter types of lambda expressions can be ignored because they can be inferred based on the context.
- The body of a Lambda expression can be an expression or a statement block.
- The input parameters of lambda expressions are involved in type inference and method overload analysis.
- Lambda expressions and expression bodies can be converted into expression trees.
- 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 use another method to write, from a piece of LINQ to SQL statement analysis to the knowledge points throughout the LINQ. Together, we can experience the fun of using LINQ.