C # Basic Supplements Series II: Explore c#7.0 new feature points with Ilspy

Source: Internet
Author: User

The first part:

C # is a generic, type-safe, object-oriented programming language. Has the following characteristics:

(1) Object-oriented: C # is a rich implementation of an object-oriented paradigm that includes encapsulation, inheritance, and polymorphism. C # Object-oriented behavior includes:

    • A unified type System
    • Classes and Interfaces
    • Properties, methods, events

(2) Type safety:C# also allows you to dynamically specify a type by using the dynamic keyword. However,C# is still a major static type language. It is a strongly typed language because its type rules are very strict, for example, it is not possible to invoke a function that interprets the int type with a parameter of type float, unless you explicitly convert float to int, which helps to prevent coding errors.

(3) Memory management: C # relies on the runtime for automatic memory management, and its common language runtime has a garbage collector that reclaims the space occupied by objects that are no longer referenced at the appropriate time, freeing the programmer to manually dispose of the object's memory. C # does not eliminate pointers, it just makes most programming tasks do not require pointers, and for high performance requirements, pointers can be used, but only in code blocks that are explicitly marked as unsafe.

(4) C # and CLR:C #is dependentRuntimeprovides memory management and exception handling,CLRallows developers to build applications in different languages. C# is one of several managed languages that are compiled into managed code. Managed code in an intermediate language orILrepresentation. CLRputILinto the machine's native code, such asX86orX64, which is usually performed before this, is called instant (Just-in-time,JIT) compilation. Lead time compilation can also be used to improve the startup time of large assemblies, or for resource-constrained devices. The existence of metadata allows the assembly to reference types in other assemblies without requiring additional files.

(5) The relationship between the CRL and the. Net Framework

The. NET framework consists of the CLR and a large number of libraries, which contain core class libraries (that is, the base Class library BCL) and application class libraries, and the Application class library relies on the core class library

Mama said so much, I believe we all know, well, below we look through the code to see what c#7.0 really let you applauded place.

Part II: c#7.0 new features

(1) Promotion of digital literals:

Numeric literals in C#7 can contain underscores for readability, which are called number separators and are ignored by the compiler.

The code is as follows:

Operation Result:

Note: binary literals can be specified with a 0b prefix.

So don't be surprised to see this, just to improve readability.

(2) Out variables and discards (receive out variables and discard out variables)

Code:

The previous wording of our writing:

Now you can write this in c#7.0:

We don't need to define the variable to receive the value outside, but write it directly in it, is not the code is more concise, another interesting place is, when a method to return multiple values, we can use out _, to selectively receive the returned value, in the above figure in the code, The method Somebigmethod returns four values, but when we receive the value it returns, we can use out _ to not receive the returned value, but to use out int x to receive the returned value, is not very flexible.

The result of the code operation is as follows:

Ilspy results:

//Methods. methodPrivateHidebysigStatic         voidMain (string[] args) cil managed {//Method begins at RVA 0x2050//Code Size (0x31). maxstack4. entrypoint. Locals init ([0] int32, [1]BOOL,            [2] int32, [3] int32, [4] int32, [5] int32)//(no C # code)Il_0000:nop//bool successful = Int. TryParse ("123", out result);Il_0001:ldstr"123"IL_0006:LDLOCA.S0Il_0008:callBOOL[System.Runtime] System.int32::tryparse (string, int32&) Il_000d:stloc.1        //Somebigmethod (out int _, out int _, out int ×, out int _);Il_000e:ldloca.s3IL_0010:LDLOCA.S4IL_0012:LDLOCA.S2IL_0014:LDLOCA.S5il_0016:call void Consoleapp1.program::somebigmethod (int32&, Int32&, Int32&, int32&) /c9>//(no C # code)Il_001b:nop//Console.WriteLine (x);Il_001c:ldloc.2Il_001d:callvoid[System.console]system.console::writeline (Int32)//(no C # code)Il_0022:nop//Console.WriteLine (result);Il_0023:ldloc.0Il_0024:callvoid[System.console]system.console::writeline (Int32)//(no C # code)Il_0029:nop//Console.readkey ();Il_002a:call valuetype [System.console]system.consolekeyinfo [System.console]system.console::readkey () Il_002f:pop//(no C # code)Il_0030:ret}//end of Method Program::main

(3) Patterns

Function: You can use the IS operator to introduce a variable called a pattern variable. Do not understand, see an example to understand.

The code is as follows:

Parsing: X is the function of string s: if x can be converted to a string converted to a value assigned to S, the result of the output is the length of the string.

The switch's declaration also supports this pattern, and you can use the When clause to specify the condition with the following code:

Operation Result:

Parsing: Foo2 (9) is passed 9, is the int type, so enters into the first case clause, so the result of the final output is: It's an int!, this explanation to 0 points, below we through Ilspy to see what this syntax sugar exactly is what, as shown:

I will not explain, we see a look at, is not want to shoot the thigh, TM originally so simple!!!

(4) Native method (local methods)

Function: A local method is a method declared inside another function. Here I give the English, because this way gives is the most accurate, Chinese translation out of TM can not understand.

Operation Result:

Parse: Defines a local method, the return value type is an int passed in the parameter is value, the return value is: value*value*value+i

Cube (2), the call passed in the value 2, so the final computed value is 2*2*2+9=17

Note: The local method is visible only to the containing function, and the variable that contains the local method can be used.

Ilspy the results of the anti-compilation:

It can be seen that in calling Cube (2), it is eventually compiled into a cube (2,ref xx), but the internal implementation of the <writecubes>g__cube|3_0 method is not visible.

(5) C # 6 describes the method's "fat-Arrow" syntax, which can be used in read-only, properties, operators, and indexers. C # 7 extends this to constructors, read/write properties, finalizers

Code:

Ilspy Code results:

(6) For C # 7, perhaps the most significant improvement is explicit tuple support

Role: Tuples provide a simple way to store a set of related values

Code:

Operation Result:

Parsing: var Bob = ("Bob", 23); Defines a tuple that you can use with Bob. Item1 to access the first parameter, you can use Bob. ITEM2 to access the second parameter, but the question comes, why can you access it like this???

Ilspy results:

As you can see, tuples are actually a valuetuple<,> generic type, where string int is determined by the type of your value, so why use Item1 and Item2 to access the corresponding value?

First Item1 and Item2 are people valuetuple<t1, t2> definition, then why I visit Item1 is "Bob", that is because in the constructor, the "Bob" assignment to Item1, so understand it.

You can also see that a tuple is a struct, which is a value type. In this case, the tuple's point is not finished, because of the compiler's magic, the tuple element can be named the following form:

Ilspy results:

With tuples, functions can return multiple parameters without resorting to out parameters:

Operation Result:

Ilspy results:

Note: Tuples implicitly support anti-parsing patterns, so they can be easily decomposed into a single variable. We can rewrite the previous main method so that the tuples returned by Getfileposition are assigned to two local variables: row and Cloum:

Operation Result:

Ilspy Result: (the result is the same as above)

OK, here's the tuple, let's see how to throw an exception.

(7) Throwing exceptions

Function: before c#7, throw is always declared, and now it can appear in a function body as an expression , and it can also appear in a ternary expression.

Ilspy results:

(8) Interpolation of strings

Directly on the code:

If you want to display multiple lines, you can write this:

Note: The $ character must be before the @ sign.

Ilspy results:

Simple I will not say more, continue the following knowledge points.

(9) Exception filter (Exception filters)

Role: Allows you to apply a condition in a catch.

(10) referencing local variable ref Locals

Role: A very important point is introduced in c#7.0, whereby you can define a local variable that references an element in an array or a field in an object.

Code:

Note: Ref Locals must be an element, field, or local variable in an array, and cannot be a property. It is usually used in conjunction with ref returns.

Operation Result:

Parsing: Ref int age Labels This variable as a reference type variable.

(one) Ref Returns

Function: You can return a ref local in a method, which is called a ref return

Code:

Operation Result:

Parsing: private static ref int GetX () is actually a method that returns a value of int32& (that is, a INT32 type that flags a memory pointer), that is, to return an address so that when I modify the value it is actually the value of the modified X.

Ilspy results:

Note: Ldsflda int32: Is the address of a static field x is pressed into the stack, RET, and then returned, in the main method, after calling the above method, from the top of the stack to remove the value, stored in the local variable list index position 0 inside.

Then take the value of the index position in the local variable to 0, and press into the stack, note that the focus, STIND.I4 is the LDC.I4.S 9 value of the address stored down, so that the value of the X is changed. So this int32& is actually the address of a variable, which is what we usually call pointers.

All right, here's basically c#7.0 the new functionality is almost there, follow-up I will continue to add c#7.0 new knowledge points, hope to help you! Thank you.

Finally, you are welcome to join my c#+.net core English book translation group, I will not regularly through the blog to update the translation of English materials, I hope to get the latest C # knowledge, but also for you and I have been improved.

Reference book: "C 7.0 in a nutshell 7th Edition"

Guo Yan

Source: http://www.cnblogs.com/runningsmallguo/

The copyright of this article is owned by the author and the blog Park, welcome reprint, but without the consent of the author must retain this paragraph, and in the article page obvious location to give the original link.

C # Basic Supplements Series II: Explore c#7.0 new feature points with Ilspy

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.