C #4.0 overview of new features

Source: Internet
Author: User

Looking back at the development history of C #, C #1.0 completely imitates Java and retains some features of C/C ++, such as struct, Which is easy for new scholars to use; C #2.0 has added generics, which is exactly the same as Java 3.0's generics. C # has added a bunch of syntactic sugar and has introduced Linq without modifying the CLR, although many projects are not used for a variety of reasons such as performance, it is very suitable for the rapid development of small programs, reducing the workload of programmers and improving the readability of the Code; C #4.0 adds the Dynamic Language Feature, from which you can see the shadows of many dynamic languages such as javascript and python. Although the path from static language is becoming more and more different, these features also aim to improve the productivity of programmers. As for whether it is accepted or not, let's talk about time.

PS: there is also an episode of version number-corresponding to VS2008. net Framework is 3.5, C # is 3.0, CLR is 2.0, and it is chaotic. MS finally decided to unify these three versions into 4.0 in VS2010, so CLR3 finished ......
 
Dynamically Typed Object
C #4.0 adds the dynamic keyword. You can declare that the static type of a variable is dynamic ).
If you do not know the type of a variable before 3.0, but want to call a method of it, reflection is generally used:
Object calc = GetCalculator ();
Type calcType = calc. GetType ();
Object res = calcType. InvokeMember ("Add ",
BindingFlags. InvokeMethod, null,
New object [] {10, 20 });
Int sum = Convert. ToInt32 (res );
With dynamic, You can simplify the above Code:
Dynamic calc = GetCalculator ();
Int sum = calc. Add (10, 20 );
The advantage of using dynamic is that you don't have to worry about the object Source: COM, IronPython, html dom, or reflection. You only need to know which method can be called, and the rest of the work can be left to runtime. The following is an example of calling the IronPython class:
ScriptRuntime py = Python. CreateRuntime ();
Dynamic helloworld = py. UseFile ("helloworld. py ");
Console. WriteLine ("helloworld. py loaded! ");
Dynamic can also be used in variable transmission. runtime automatically selects the most matched overload method.
Here is a demo: copy a piece of javascript code to the C # file, change var to dynamic, change function to void, and then change the calling method of the constructor (new type () to win. new. type (), remove win from javascript. prefix (because it is already the C # method), you can run it directly.
Dynamic is implemented based on the IDynamicObject interface and the DynamicObject abstract class. Dynamic Methods and attribute calls are all converted to call methods such as GetMember and Invoke.
Public abstract class DynamicObject: IDynamicObject
{
Public virtual object GetMember (GetMemberBinder info );
Public virtual object SetMember (SetMemberBinder info, object value );
Public virtual object DeleteMember (DeleteMemberBinder info); public virtual object UnaryOperation (UnaryOperationBinder info );
Public virtual object BinaryOperation (BinaryOperationBinder info, object arg );
Public virtual object Convert (ConvertBinder info); public virtual object Invoke (InvokeBinder info, object [] args );
Public virtual object InvokeMember (InvokeMemberBinder info, object [] args );
Public virtual object CreateInstance (CreateInstanceBinder info, object [] args); public virtual object GetIndex (GetIndexBinder info, object [] indices );
Public virtual object SetIndex (SetIndexBinder info, object [] indices, object value );
Public virtual object DeleteIndex (DeleteIndexBinder info, object [] indices); public MetaObject IDynamicObject. GetMetaObject ();
}
 
Named and optional parameters
This does not seem to be very difficult to implement or novel, as long as the compiler supports it (VB has long supported it ). It is estimated that the reason for joining is that the voices of the masses are too high.
Declarations with optional parameter methods:
Public StreamReader OpenTextFile (
String path,
Encoding encoding = null,
Bool detectEncoding = true,
Int bufferSize = 1024 );
The name parameter must be used at the end:
OpenTextFile ("foo.txt", Encoding. UTF8, bufferSize: 4096 );
Unlimited order:
OpenTextFile (bufferSize: 4096, path: "foo.txt", detectEncoding: false );
Improved COM Interoperability
When calling COM objects such as office objects in C #, you often need to write a bunch of unnecessary parameters:
Object fileName = "Test.docx ";
Object missing = System. Reflection. Missing. Value;
Doc. SaveAs (ref fileName,
Ref missing,
Ref missing,
Ref missing,
Ref missing,
Ref missing, ref missing, ref missing );
4.0 can be directly written:
Doc. SaveAs ("Test.docx ");
C #4.0 makes the following improvements to COM Interaction:
Automatic object-> dynamic mapping
Optional and named parameters
Indexed properties
Optional "ref" modifier
Interop type embedding ("No PIA ")
A simple explanation of and is as follows:
In a COM call, many input and output types are all objects, So that you must know the exact type of the returned object. After forced conversion, you can call the corresponding method. With the support of dynamic in 4.0, you can define variables as dynamic rather than objects when importing these COM interfaces, eliminating the need for forced type conversion.
PIA (Primary Interop Assemblies) is a. Net Assembly generated based on COM APIs. It is generally large in size. When running in 4.0, PIA does not need to exist. The compiler will determine which part of the com api is used by your program and only use PIA for packaging, directly add it to the Assembly of your own program.
Co-and Contra-Variance
I really don't know how to translate these two words.
(Thanks to the prompts of Ariex, Xu shaoxia, AlexChen, should be translated as co-variant and inverter, http://msdn.microsoft.com/zh-cn/library/ms173174 (VS.80). aspx)
In C #, the following type conversion is invalid:
IList <string> strings = new List <string> ();
IList <object> objects = strings;
Because you may do this, but the static check of the compiler cannot find the error:
Objects [0] = 5;
String s = strings [0];
4.0 when declaring the Interface and Delegate of generic, you can add the in and out keywords, such:
Public interface IEnumerable <out T>: IEnumerable
{
IEnumerator <T> GetEnumerator ();
}
Public interface IEnumerator <out T>: IEnumerator
{
Bool MoveNext ();
T Current {get ;}
}
Public interface IComparer <in T>
{
Public int Compare (T left, T right );
}
The out keyword means that T in IEnumerable <T> will only be used in the output, and the value will not be changed. In this way, converting IEnumerable <string> to IEnumerable <object> is safe.
In means that the T in IComparer <T> is only used in the input, so that the IComparer <object> can be converted to the IComparer <string> type safely.
The former is called Co-Variance, and the latter is Contra-Variance.
Use the Interface declared by out/in. Net4.0:
System. Collections. Generic. IEnumerable <out T>
System. Collections. Generic. IEnumerator <out T>
System. Linq. IQueryable <out T>
System. Collections. Generic. IComparer <in T>
System. Collections. Generic. IEqualityComparer <in T>
System. IComparable <in T>
Delegate:
System. Func <in T ,..., Out R>
System. Action <in T,…>
System. Predicate <in T>
System. Comparison <in T>
System. EventHandler <in T>
Compiler as a Service
The compiler-related API is added in 4.0, so that the string can be dynamically compiled and executed as code, just like javascript.
At the end of Video, Anders made a cool demo. It took about 20 or 30 lines of code to execute the C # statement directly on the console, define and call the function, dynamic Creation of windows form, addition of buttons and other functions, looks completely inferior to the console in Python, Ruby and other languages.
 
After n years of silence, the CLR has finally come to a new version. This time, Jeffrey Richter has no excuse for failing to release the new version of CLR via C :)

Author: "Computer Encyclopedia (only used for technology .."

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.