c#3.0 Automatic Property object initializers, collection initializers, extension methods

Source: Internet
Author: User
Tags scalar static class

Reference
New features of the C # language in Orcas: Automatic properties, object initializers, and collection initializers
New Orcas language Features: extension methods

1. Automatic properties: public class Person {
public string FirstName {get; set; }
public string LastName {get; set; }
public int Age {get; set; }
}

When the C # compiler in the Orcas version encounters an empty get/set attribute like the one above, it automatically generates a private member variable for you in the class, which implements a public getter and setter for the variable.

2. Object initializers:

person who = new Person {FirstName = "Scott", LastName = "Guthrie", age = 32};

Do not use person person = new person (); Person. Firstname= "Scott";
Nesting is of course allowed:

person who = new Person {
FirstName = "Scott",
LastName = "Guthrie"
Age = 32,
Address = new Address {
Street = "One Microsoft Way",
City = "Redmond",
State = "WA",
Zip = 98052
}
} ;

3 Collection Initializers

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 the above syntax, it automatically generates a collection insertion code for us.
namely list<persion> people = new list<person> (); Person.add (New person{...}); Person.add (New person{...});

4. Extension methods

For example, verify that a string is legitimate

General notation, define a class, implement static method IsValid (String): string email = request.querystring["email"];

if (emailvalidator.isvalid (email)) {

}

Extension methods allow:

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

if (email. Isvalidemailaddress ()) {

}

How extension methods are implemented:

public static Class Scottguextensions
{
public static bool Isvalidemailaddress (this string s)
{
Regex regex = new Regex (@ "^[/w-/.] +@ ([/w-]+/.) +[/w-]{2,4}$ ");
return regex. IsMatch (s);
}
}

Note that the string argument variable for a static method has a "This" keyword in front of it, which tells the compiler that this particular extension method should be added to an object of type "string" .
When used, use the "using" statement to introduce the namespace of the implementation that contains the extension method

The following completely reproduced, wrote a very clear extension method to use the scene continued ...

Using the new feature of extension methods to add methods to individual types opens up many useful extensibility scenarios for developers. But what makes extension methods very powerful is that they can be applied not only to individual types but also to. NET Framework, or on any base class or interface in the This allows developers to build all sorts of things that can be used throughout. NET Framework's rich, scalable framework layer extensions.

For example, consider a scenario where I want an easy, descriptive, and powerful way to check whether an object is already contained in an object collection or array. I can define a simple one. In (Set) extension method, I want to add it to. NET Framework, I can implement this "in ()" extension method in C #:

Notice how I declare the first argument of the extension method: "This object o". This indicates that this extension method should apply to all types inheriting the System.Object of the base class, which means that I can use it on every object in. Net.

The implementation of the above "in" method allows me to check whether a specified object is contained in a IEnumerable sequence passed in as a method parameter. Because all the. NET collection and arrays are implemented with the IEnumerable interface, now I have a useful, descriptive way to check whether an arbitrary object belongs to any. NET collection or array.

Then I can use this "in ()" method to see if a particular string is in an array of strings:

I can also use it to check whether a particular ASP.net control is in a container control collection:

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

Notice that you can even use an extension method on a basic data type value like an integer value of 42. Because the CLR supports automatic boxing/unboxing of numeric types, extension methods can be used directly on numeric values and other scalar data types.

You can probably start with the example above, the extension method can contribute to some very rich and descriptive extensibility scenarios. When made for. NET, they can contribute to some very good framework and combination scenarios that are specific to a domain (domain specific). built-in System.Linq extension method

A built-in extension method library that is published with. NET during the Orcas period is a very powerful query extension method that allows developers to query any data. These extension method implementations are located under the new System.Linq namespace and define standard query operator extension methods that can be used for. NET developers are used to easily query XML, relational databases,. NET objects, and any other data structure type.

Here are some of the benefits of extensibility models that use 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, allowing 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 that is defined for LINQ as part of a separate query. Our custom in () method looks just like the standard method provided by the System.Linq namespace.

3 It is extensible and allows to be used with any data provider type. For example, any existing ORM engine like NHibernate or Llblgen can implement LINQ's standard query operators to allow LINQ queries to their existing ORM implementations and mapping engines. This allows developers to learn a common way to query data, and then use the same skills for a wide variety of rich data storage implementations.

I'm going to do a little more demonstration of LINQ in the next few weeks, but I want to leave you with a few examples of how to use several built-in LINQ query extension methods for different types of data: using scene one: in memory. NET object using the Linq extension method

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

Then create and populate a "people" set, like this:

Then I can use the standard "Where ()" extension method provided by System.Linq to get those "person" objects in this collection where the first character of the FirstName is "S", like this:
where () is the extension method. Takes a function as a parameter.

The above new P => syntax is An example of a "lambda expression", a more concise development of support for the C # 2.0 anonymous method , allowing us to easily express query filtering through an argument (in this case, We say we want to return only the first character of a string of FirstName attributes is the person object of the "S" letter. The above query then returns a sequence containing 2 objects, Scott and Susanne.

I can also use the new "Average" and "Max" extensions provided by System.Linq to write code that determines the average age of the people in my collection, as well as the oldest people, like this:

Use Scenario two: Use LINQ extension methods on XML files

It is probably rare for you to create a hard-write (hard-coded) collection of data manually in memory. More likely, you'll get data from a 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 to load this Xml file into a DOM and then access it, or use a low-level XmlReader API to manually analyze it myself. Or, in Orcas, I can now use the SYSTEM.XML.LINQ implementation (that is, XLinq), which supports the standard Linq extension method, to parse and process Xml more gracefully.

The following code example shows how to use LINQ to get all the <person> XML elements with the first letter "S" of a value that contains a child node:

Note that it uses a Where () extension method that is identical to the object example in memory. Now it returns a sequence of "XElement" elements, Xelemen is an XML node element of no type . Or I can rewrite the query expression to construct the data shape through the LINQ Select () extension method, which is mapping, mapping the filtered XElement element sequence to the object sequence :

The code above will do all the work required to open, parse, and filter the XML, and then return a strongly typed person object sequence.

I can also use the same average () and Max () LINQ extension methods as before to compute the average age of <person> elements in an XML file, as well as the maximum age, like this:

Instead of parsing the XML file manually, XLinq can not only handle the analysis for me, it can also use low-level XmlReader when estimating LINQ expressions, rather than using DOM to parse files. This means that it is extremely fast and does not allocate a lot of memory. using Scenario Three: Using LINQ extension methods for Databases

Suppose we have an SQL database that contains a table called "people" with the following data definitions:

I can quickly create a "person" class that maps to a database by using the new LINQ to SQL WYSIWYG (WYSIWYG) ORM Designer in Visual Studio:

Then I can use the same LINQ Where () extension method I used previously for objects and XML files to get the strongly typed "person" object sequence of FirstName's first character "S" from the database:

Note that the query syntax is exactly the same as the object and the XML scene.

I can then use the same LINQ Average () and Max () extension methods as before to get the average and maximum values from the database, like this:

To make the above code example work, you don't need to write any SQL code yourself. The LINQ to SQL Object Relational Mapper provided in orcas handles fetching, tracking, and updating objects that map to your database data definition and stored procedures. As long as you filter and shape the results using any LINQ extension method, LINQ to SQL executes the SQL code needed to get the data (note that the average and max extension methods above obviously do not return all rows of data from the datasheet). They use the TSQL aggregate function to compute the values in the database and then return only one scalar value.

Watch a video I made in January that demonstrates how LINQ to SQL dramatically improves data productivity in orcas. In the video, you can also see the actual demo of the WYSIWYG ORM designer as seen in the new LINQ to SQL, and the complete IntelliSense provided by the Code editor when writing LINQ code for the data model.

Related Article

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.