Explore c#7.0 new feature points using Ilspy

Source: Internet
Author: User
The first part:

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

(1) object-oriented: C # is a rich implementation of object-oriented paradigm, which 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 types to be dynamically specified through the dynamic keyword. However, C # is still a major static type language. It is a strongly typed language because its type rule is very strict, for example, it is not possible to use a float-type argument to invoke a function that interprets the int type, unless you explicitly convert float to int, which helps prevent coding errors.

(3) Memory management: C # relies on automatic memory management at runtime, and its common language runtime has a garbage collector that frees up the space for objects that are no longer referenced in the right time, freeing up the memory of the programmer to manually release the object. C # does not eliminate pointers, it simply makes most programming tasks unnecessary to use pointers, and can use pointers where performance is high, but only allowed in blocks of code that are explicitly marked as unsafe.

(4) C # and clr:c# are dependent on the memory management and exception handling provided by runtime, and the CLR allows developers to build applications in different languages. C # is one of several managed languages that are compiled into managed code. Managed code is represented in an intermediate language or IL. The CLR converts il into native code for machines, such as X86 or X64, which is usually performed before, which is called Just-in-time (Just-in-time,jit) compilation. Lead time compilation can also be used to improve the startup time of large assemblies, or resource-constrained devices. The presence of metadata allows assemblies to refer to types in other assemblies without the need for additional files.

(5) 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 the Application class library, and the Application class library relies on the core class library

The little Mama said so much, I believe everybody knows, OK, the following we look through the code to see c#7.0 What make you applauded place. Part II: c#7.0 new features

(1) Increase in the number of literal:

Numeric text in C#7 can contain underscores to improve readability, which is called a numeric separator and is ignored by the compiler.

The code is as follows:

Run Result:

Note: binary text 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:

We used to:

Now you can write this in c#7.0:

We don't need to define the variables to receive the value in the outside first. It is written 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 returned values, in the above figure in the code, Method Somebigmethod returns four values, but when we receive the value returned by it, we can use out _ not to receive the returned value, but to use out int x to receive the returned value is not very flexible.

The results of the code run are as follows:

Ilspy results:

Methods

. method private Hidebysig static

void Main (

String[] Args

) CIL managed

{

Method begins at RVA 0x2050

Code size (0x31)

. maxstack 4

. 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.S 0

il_0008:call bool [System.runtime]system.int32::tryparse (String, int32&)

Il_000d:stloc.1

Somebigmethod (out int _, out int _, out int x, out int _);

IL_000E:LDLOCA.S 3

IL_0010:LDLOCA.S 4

IL_0012:LDLOCA.S 2

IL_0014:LDLOCA.S 5

Il_0016:call void Consoleapp1.program::somebigmethod (int32&, Int32&, Int32&, int32&)

(no C # code)

Il_001b:nop

Console.WriteLine (x);

Il_001c:ldloc.2

Il_001d:call void [System.console]system.console::writeline (Int32)

(no C # code)

Il_0022:nop

Console.WriteLine (result);

il_0023:ldloc.0

Il_0024:call void [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. Don't understand, see an example to understand.

The code is as follows:

Parsing: x is string s function is: if x can be converted to string converted to the value assigned to s, so 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 conditions, as follows:

Run Result:

Resolution: Foo2 (9) passed over is 9, is the int type, so it goes into the first case clause, so the result of the final output is: it's an int!, this explanation gives 0 points, below we pass ilspy to see what this kind of grammatical candy is exactly, the following picture shows:

I do not explain, we see it, is not want to film the thigh, TM originally so simple ...

(4) Native method (local methods)

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

Run Result:

Parsing: Defines a local method that returns the value type int the parameter is value and the return value is: value*value*value+i

Cube (2), which invokes the passed value of 2, so the final computed value is 2*2*2+9=17

Note: The local method is visible only to the containing function, and you can use a variable that contains the local method.

Ilspy the results of the reverse compilation:

It can be seen that the call to Cube (2) is eventually compiled into a cube (2,ref xx) Such a method, but does not see the internal implementation of the <writecubes>g__cube|3_0 method.

(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 notable improvement is explicit tuple support

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

Code:

Run Result:

Parsing: var Bob = ("Bob", 23); a tuple is defined, and you can use Bob. Item1 to access the first argument, you can use Bob. ITEM2 to access the second parameter, but the problem is why you can access it like this ...

Ilspy results:

As you can see, the tuple is actually a valuetuple<,> generic type, where string int is determined by the type of your value, so why Item1 and Item2 can be used to access the corresponding values.

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

In addition, you can see that the tuple is a struct, which belongs to the value type. Talking about the point of the tuple, the tuple elements can be named in the following form because of the magic of the compiler:

Ilspy results:

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

Run Result:

Ilspy results:

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

Run Result:

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

Okay, so here's the tuple, and then let's see how to throw the exception.

(7) Throw an exception

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

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 precede the @ symbol.

Ilspy results:

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

(9) Exception filter (Exception filters)

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

(10) referencing local variable ref Locals

Role: c#7.0 introduces a very important point in which you can define a local variable that refers to an element in an array or to a field in an object.

Code:

Note: Ref Locals must be an element, field, or local variable in the array, not an attribute. It is usually used in conjunction with ref returns.

Run Result:

Parsing: Ref int age is a variable that refers to a reference type when the variable is annotated.

(one) Ref Returns

Function: You can return a ref local in one method, this way called ref return

Code:

Run Result:

Resolution: private static ref int GetX () is actually a method of returning a value of int32& (a type of INT32 that marks a memory pointer), which 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: The address of a static field x is pressed into the stack, RET, and then returned, in the main method, when the above method is invoked, the value is fetched from the top of the stack and stored in the index position 0 of the local variable list.

Then take the local variable index position of 0, and into the stack, pay attention to the point, Stind.i4 is the LDC.I4.S 9 value of the address stored, so that the value of x changed. So this int32& is actually the address of a variable, which is what we usually call a pointer.

Okay, so here's basically c#7.0 new features to talk about, follow-up I will continue to add c#7.0 new knowledge points, I hope to help you. Thank you.

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

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

Related articles:

C # features that have been popular over the years

C # 7 Programming patterns and practices

C # 7.1, 7.2 feature tracking

C # 7.2 and 8.0 Road Map

Original address: https://www.cnblogs.com/runningsmallguo/p/8972678.html

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.