C #3.0 automatic property object initiator, set initiator, and Extension Method

Source: Internet
Author: User

Reference
New Features of C # language in orcas: Automatic attributes, object initializer, and set initializer
New orcas language features: Extension Method

1. Automatic attributes:

Public class person {
Public String firstname {Get; set ;}
Public String lastname {Get; set ;}
Public int age {Get; set ;}
}

When the C # compiler in orcas encounters an empty GET/set attribute like above, it will automatically generate a private member variable for you in the class, implement a public getter and setter for this variable

2. Object initializer:

Person = new person {firstname = "Scott", lastname = "Guthrie", age = 32 };

You do not need to use person = new person (); person. firstname = "Scott ";
Of course, nesting is also allowed:

Person = new person {
Firstname = "Scott ",
Lastname = "Guthrie"
Age = 32,
Address = new address {
Street = "One Microsoft Way ",
City = "Redmond ",
State = "wa ",
Zip/98052
}
};

3. Set Initiator

List <person> People = new list <person> {
New person {firstname = "Scott", lastname = "Guthrie", age = 32 },
New person {firstname = "bill", lastname = "Gates", age = 50 },
New person {firstname = "Susanne", lastname = "Guthrie", age = 32}
};

When the compiler encounters such a syntax, it will automatically generate the encoding for the set.
That is, list <persion> People = new list <person> (); person. add (new person {...}); person. add (new person {...});

4. Extension Method

For example, verify that a string is valid

Generally, define a class to implement the static method isvalid (string ):

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

If (emailvalidator. isvalid (email )){

}

The extension method allows:

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

If (email. isvalidemailaddress ()){

}

How to Implement the extension method:

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 there is a "This" keyword before the string parameter variable of the static method, which tells the compiler that this specific extension method should be added to an object of the "string" type..
In use, use the "using" statement to introduce the namespace containing the implementation of this extension method.

The following is a full record, which is clearly written.

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.

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 create and fill in a "people" set, as shown in the following code:

Then I can useStandard "where ()" extension method provided by system. LINQTo get the first character of firstname in this set is the "person" object of "S", as shown in the following code:
Where () is the extension method! Take the function as a parameter!

The new p => syntax above isAn example of "lambda expressions" is a more concise development of C #2.0 anonymous method supportAllows us to easily express query filtering through a real parameter (in this case, we mean that we only want to return a string of the first character of the firstname attribute is the person object of the "S" letter ). 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 itReturns a sequence of "xelement" elements. 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,It is actually a ing, which maps the filtered xelement sequence to the object sequence.:

The above code will open, analyze, and filter XML, and then return all the work of a strong person object sequence.

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 to SQL object CER 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, and LINQ to SQL will execute the SQL code required to obtain data (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 LINQ to SQL WYSIWYG ORM designer, as well as the complete intelliisense provided by the Code Editor for compiling the data model in the time of writing the LINQ code.

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.