Summary of new features of. Net 4.0

Source: Internet
Author: User
Tags access properties array definition

From: http://developer.51cto.com/art/200907/134082.htm

Every new version of. NET Framework brings us many new features that make. net more powerful and easy to use. Net 4.0 is no exception. When we focus on individual new features, we will see that Microsoft is learning from each other between C # and VB. NET to fulfill its promise of "joint development.

 

Dynamic query (Dynamic lookup) (C # newly introduced)

 

As mentioned above, C # adds a new static type called dynamic. Although we can run it in many cases, it is not very common. You can regard the dynamic type as an object that supports delayed binding.

Dynamic car = getcar (); // get a reference to the Dynamic Object
Car. Model = "Mondeo"; // assign a value to a property (also works for fields)
Car. startengine (); // calling a method
Car. Accelerate (100); // call a methods with Parameters
Dynamic person = car ["driver"]; // getting with an Indexer
Car ["passenger"] = createpassenger (); // setting with an Indexer

 

During compilation, fields, attributes, and methods of dynamic objects are basically ignored. That is to say, a compilation error is not prompted during compilation even if a member is unavailable. Because the information is only available at runtime,. Net knows how to use DLR to parse dynamic members. C # is still a static language so far, because of performance considerations. The new dynamic type does not mean you can discard the static type completely. It is just a tool you can use when you have to use the dynamic type.

 

Named and optional parameters (introduced in C)

 

The naming and optional parameters have been stored in VB. NET for a long time, and now C # supports them. As the name suggests, you can selectively PASS Parameters to methods or constructors. If you choose not to pass the parameter, the previously defined default value will be used for the called method. In C #, to change a method parameter to an optional parameter, you only need to assign it a default value.

Public void createbook (String title = "No title", int pagecount = 0, string ISBN = "0-00000-000-0 ")
{
This. Title = title;
This. pagecount = pagecount;
This. ISBN = ISBN;
}

 

You can call the createbook method defined above in the following forms

Createbook ();
Createbook ("some book title ");
Createbook ("some book title", 600 );
Createbook ("some book title", 600, "5-55555-555-5 ");

 

Note that the location of reliable parameters is very important. In this example, the title must appear with the first parameter, page count as the second, and ISBN as the third. If you want to call createbook but only pass the ISBN number parameter, You can implement this in two ways. The first solution is to create an overload method with ISBN as the parameter. This method is a classic method, but it is also tedious. The second solution is to use the named parameter, which is much simpler than the previous one. Naming parameters allow you to pass parameters in any order. You only need to provide the parameter name. In this case, you can call the method in the following forms:

Createbook (ISBN: "5-55555-5555-5 ");
Createbook ("book title", ISBN: "5-55555-5555-5 ");
Createbook (ISBN: "5-55555-5555-5", title: "book title", pagecount: 600 );

 

Please note that you can use the positional parameter first, and then use the second method we demonstrated above, but if you use the named parameter ), it must be used all the time.

 

Dynamic import (dynamic import) (C # newly introduced)

 

Almost all interfaces exposed through the com api use a variable data type, which was previously represented by a data type object in C. Before that, there was no way to process dynamic types in C #, so the processing of these types became a conversion between various data types. But now C # supports dynamic types. You can import COM components as dynamic objects, so that you can directly set attributes and call methods without explicitly converting object types.

 

Omitted reference parameter (ref parameter) (C # newly introduced)

 

Another by-products of calling com APIS is that parameters of a large number of methods must be passed through references. In most cases, we just want to pass a value to the method, regardless of what it returns. However, you still need to create many temporary variables to save the results. This monotonous job can be handed over to interns to gain the so-called "practical work experience ". In C #4.0, you can directly pass the parameter value to com. the compiler will automatically generate temporary variables for you. This saves time for developers and allows interns to lose many so-called "practical work experience ".

 

Co-variance and contra-variance (C # and VB. NET)

 

One of the most striking problems of generic (generics) has been solved in. Net 4.0. In the past, if you had an object that supports ienumerable <string> and then want to pass it to a method that requires ienumerable <Object> parameters, you would find that this cannot be done at all. You must generate a new object that supports ienumerable <Object>, fill it with the string obtained from the ienumerable instance, and then pass it to the method. As we all know, strings are more specific types than objects, So we naturally consider list <string>
Ienumerable <string> interface and ienumerable <Object> must be supported. The result is that the compiler does not. However, in. Net 4.0, this problem has been solved. This is because generic (generics) now supports covariant and variant changes.

Both covariant and inverter are related to program type security and performance. In a rough sense, the covariance indicates that an object has a weak derivation (less derived). If the out keyword is added before a parameter of the regular type, the Association is changed. The covariant types are restricted to be used in the output location, that is, they only appear in the results of calling methods or access properties. These are the only places where the covariant type can be called "security", or the only place where additional type checks are not required during compilation. In. net4.0, The ienumerable <t> interface is equivalent to ienumerable <out T> because ienumerable is a covariant. This also means that the following example is completely valid:
Ienumerable <string> strings = getstrings ();
Ienumerable <Object> objects = strings;

Contra-variance indicates that an object can be considered as more derived. It can be expressed by adding the in keyword before the common parameter type. The inverter type is restricted to the input position. That is to say, it can only appear in method parameters or must have the "write only" attribute. In. Net 4.0, The icomparer <t> interface is now changed to icomparer <in T>, because icomparer is a variant. This concept is not easy to understand, but understanding their meaning can save a lot of trouble in generic conversion. For the covariant and inverter in C #4.0, refer to the C #
4.0.

 

Requires no primary interoperability assembly (primary InterOP assemblies) compilation (C # And New introduction to VB. NET)

 

Primary InterOP assemblies (PIA) is an assembly provided by the vendor. It is located between the COM component and. NET Framework. The most widely known is the Microsoft Office primary interoperability assembly. During development, if your Assembly contains references to Pia, you must attach PIA to the Assembly or provide instructions on how to obtain Pia. The new features of C # and VB. NET allow you to directly embed Pia into your own program set, greatly simplifying deployment. Pia is usually relatively large, so the entire inclusion may make your Assembly bloated. Fortunately, the compiler will optimize the choice of embedding only the part of Pia you actually use, so that you can effectively reduce the PIA point area (footprint) when only a small part of Pia is used ).

 

Below is the VB. NET Section

 

Support for anonymous methods (introduced in VB. NET)

 

Another new feature introduced by VB. NET is the built-in (Inline) or anonymous (anonymous) method. The name of the anonymous method is very appropriate, because it allows you to directly define sub-methods (subs) and functions, instead of adding a top-level (top-level) to your class) so that the method is hidden (that is, anonymous ). The anonymous method can also access all the available variables in the code block where it is located. In this way, when defining an anonymous method, it can be passed in and returned without parameters. Currently, you can define an anonymous function where the addressof keyword is used to point to a method. Therefore, it is most useful for event processing, as shown in the following example:

Dim mytimer as new system. Timers. Timer (1000)
Dim seconds as integer = 0
 
Addhandler mytimer. elapsed,
Sub ()
Seconds + = 1
Console. writeline (seconds. tostring () & "seconds have elapsed ")
End sub
 
Mytimer. Start ()
Console. writeline ("press any key to exit ")
Console. Readline ()

Note that the timeout event handler for the definer is embedded, and the embedded method directly accesses the variables defined outside it. You can also define embedded functions:
Dim F = function (a as integer, B as integer)
Return A + B
End Function
 
Dim X = 10
Dim y = 20
Dim z = f (x, y)

If an embedded function makes sense in the context of a code block, it is indeed very convenient to use, but it may affect the reusability of the program.

 

Implicit line continuation (introduced in VB. NET)

 

When you look at the C # code, you can see at a glance where the end of the statement is, because it uses a semicolon as the statement Terminator. VB also has a statement Terminator, but its Terminator is a carriage return. Each statement is assumed to be in the same row. If you want to break this rule, you have to use an underscore to show that the next line is the continuation of this statement. People who have written the VB. Net program should feel that this method is both troublesome and affects the appearance of the Code.
Dim text as string = "Wouldn't it be nice "&_
"If you didn't have "&_
"Put an underscore "&_
"Continue to the next line? "

Okay. Now we don't need to do this anymore. VB. NET now supports implicit end-to-end (implicit line continuation ). When the compiler finds an incomplete statement in a row, it automatically checks whether the content of the next row contains the remaining part of the statement.
Dim text as string = "Wouldn't it be nice "&
"If you didn't have "&
"Put an underscore "&
"Continue to the next line? "&
"Sweet! Now you can! "

If you still like nostalgia, you can still use the original display statement method, which is still available now. And sometimes we can have to use it, because the compiler may not be able to determine whether the next row is a continuation. Rest assured that this situation will not happen frequently, and the compiler will notify you if this happens.

 

Simplified attribute syntax (New introduction to VB. NET)

 

The simplified attribute syntax is another feature that introduces VB. NET from C. The attribute definition usually looks like this:
'Field
Private _ name as string

'Property
Public property name () as string
Get
Return _ name
End get
Set (byval value as string)
_ Name = Value
End set
End Property

It can be abbreviated:
Public property name () as string

This reduces the number of lines of code from nine to one. If you choose the simplified method, you must note that you cannot access the region where the value is stored, which may cause problems when passing values by reference. In this case, you can recover to the normal writing or use a temporary variable at any time.

 

Array type inference and multiple arrays (jarged arrays) (new VB. NET)

 

VB. NET now supports array type judgment and multi-array definition syntax. This means that you do not explicitly declare its type when defining an initial value. The compiler can automatically determine its type. For example:
Dim numbers = {1, 1, 2, 3, 5, 8, 13, 21, 34}

When you see this array, you can quickly determine that it is an integer type. Now the compiler can make this judgment exactly as we do.
Dim numbers = {1, 1, 2, 3, 5.0, 8, 13, 21, 34}

When the compiler sees the example above, it will find that 5.0 is not an integer, so the array type is double. Type determination can also be used for matrices:
Dim names = {"Sarah", "Jane", "Mary", "Susan", "Amanda "},
{"Bob", "Joe", "Dustin", "Richard", "Nick "}}

The compiler can infer that string () is the type in the above example. In multiple arrays, you may encounter some problems. You can regard a two-dimensional matrix as a matrix with the same number of columns in each row. The number of columns in each row of multiple arrays is variable, so it is different from the matrix. You may think you can define such a multi-array:
Dim names = {"Sarah", "Jane", "Mary", "Susan", "Amanda "},
"Bob", "Nick "}

However, you will find that the compiler throws an error saying "three elements are missing during array initialization" (array initialiser is missing 3 elements) because the compiler treats it as a matrix by default. To define multiple arrays, you only need to enclose these rows in a pair of braces:
Dim names = {"Sarah", "Jane", "Mary", "Susan", "Amanda "},
{"Bob", "Nick "}}

Now the compiler can infer that its type is string (), which is the correct type of multiple arrays.

 

From keyword (New VB. NET Introduction)

 

Now that initialization is done, we have to talk about the from keyword introduced in VB. NET. When you create a dictionary, table, or other object composed of many objects, you usually create the object first, and then fill it with the appropriate item. Now, with the from keyword, you don't have to call the add method repeatedly. It can automatically help us call the add method to fill the list. Therefore, you do not need to write as follows:
Dim colors as new list (of string)
Colors. Add ("red ")
Colors. Add ("green ")
Colors. Add ("blue ")

Just scale down to this point:
Dim colors as new list (of string) from {"red", "green", "blue "}

Undoubtedly, it actually calls the add method, that is, it can work on any object containing the add method. In fact, you can even use the extension method to create an add method or overload an add method. If the input parameters match the method declaration, they will be used by the from keyword. In the previous example, a list object only needs the add method of one parameter. The parameter value is the string you want to add to the table. If you have an add method with multiple parameters, you can do the same as defining a matrix when passing in the parameter. The following example shows how to use the add method and a dictionary object.
Dim colors2 as New Dictionary (of string, string) from {
{"Red", "ff0000 "},
{"Green", "00ff00 "},
{"Blue", "0000ff "}}

Because the add method of dictionary contains two parameters, key and value, we must input a set of parameters in the from statement. In addition, you must ensure readability when using the from keyword. In some specific cases, you may still want to use the add method.

 

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.