Dry goods are coming! C #7.0 new features (available in VS2017 ),

Source: Internet
Author: User

Dry goods are coming! C #7.0 new features (available in VS2017 ),

Preface

Microsoft released the new VS 2017 yesterday .. there are a lot of things that come along .... NET new version ASP. NET new version... and so on .. too many .. actually not digested ..

Share with me the new features of C # December 2016 that have been published in 7.0. Although they have been released very early, this IDE does not support them ..

However, it was perfectly supported in yesterday's VS2017.

E Good, move the official introduction address: https://docs.microsoft.com/zh-cn/dotnet/articles/csharp/csharp-7

FirstRelated syntax:

1. out-variables (Out variable)

2. Tuples (Tuples)

3. Pattern Matching (Matching mode)

4. ref locals and returns (returns local variables and references)

5. Local Functions (Local function)

6. More expression-bodied members (More function member expression bodies)

7. throw Expressions (exception expression)

8. Generalized async return types (general asynchronous return type)

9. Numeric literal syntax improvements (Numeric text syntax improvement)

Body

1. out-variables (Out variable)

Previously, when we used the out variable, we had to declare it externally before passing in the method, similar to the following:

String ddd = ""; // declare the variable ccc. StringOut (out ddd); Console. WriteLine (ddd );

In C #7.0, we do not need to declare it directly while passing the parameter, as shown below:

StringOut (out string ddd); // declare Console. WriteLine (ddd); Console. ReadLine ();

2. Tuples (Tuples)

In. NET4.0, Microsoft gave us a solution called tuples for multiple return values. Similar code is as follows:

static void Main(string[] args) { var data = GetFullName(); Console.WriteLine(data.Item1); Console.WriteLine(data.Item2); Console.WriteLine(data.Item3); Console.ReadLine();}static Tuple<string, string, string> GetFullName() { return new Tuple<string, string, string>("a", "b", "c");}

The code above shows a method that returns a triple containing three strings. However, when we get the value, the heart is blown up when we use it. What is the ghost of Item1, Item2, and Item3, although it meets our requirements, it is not elegant

In C #7.0, Microsoft provides a more elegant solution: (Note: You need to reference System. ValueTuple through nuget) as follows:

Static void Main (string [] args) {var data = GetFullName (); Console. writeLine (data. a); // you can obtain the value of Console using a name. writeLine (data. b); Console. writeLine (data. c); Console. readLine ();} // The method is defined as multiple return values and named private static (string a, string B, string c) GetFullName () {return ("", "B", "c ");}

Deconstruct tuples. Sometimes we don't want to use var to retrieve them anonymously. How can we get abc? We can:

Static void Main (string [] args) {// defines the deconstruct tuples (string a, string B, string c) = GetFullName (); Console. writeLine (a); Console. writeLine (B); Console. writeLine (c); Console. readLine ();} private static (string a, string B, string c) GetFullName () {return ("a", "B", "c ");}

3. Pattern Matching (Matching mode)
In C #7.0, the matching mode is introduced. for an object type, we want to determine whether it is an int. If it is an int, we add 10. Then, the output must be as follows:

Object a = 1; if (a is int) // is judge {int B = (int) a; // split int d = B + 10; // Add 10 Console. writeLine (d); // output}

In C #7.0, the first step is a small extension of is. We just need to write it like this, as shown below:

Object a = 1; if (a is int c) // here, after it is judged as int, it is directly assigned to c {int d = c + 10; Console. writeLine (d );}

Is this convenient? Especially those who often use reflection ..

So the question is, which excavator technology is strong ?! (Keke, just kidding)

Actually, what if there are multiple types of matching? Multiple if else? Of course there is no problem. However, Microsoft's father also provides a new switch method. Let's take a look at the following:

We define an Add method, using Object as a parameter, and return a dynamic type.

 static dynamic Add(object a) { dynamic data; switch (a) { case int b:  data=b++;  break; case string c:  data= c + "aaa";  break; default:  data = null;  break; } return data; }

Run the following command to input the int type:

object a = 1;var data= Add(a);Console.WriteLine(data.GetType());Console.WriteLine(data);

Output:

We pass in the String type parameter, the code and output are as follows:

object a = "bbbb";var data= Add(a);Console.WriteLine(data.GetType());Console.WriteLine(data);

With the code above, we can see how smooth and powerful the new switch method is.

Case When filtering in matching mode

Some friends may ask. Since we can match the type in the Switch, can we filter the values by the way? Of course, the answer is yes.

Modify the Switch Code as follows:

 switch (a) { case int b when b < 0:  data = b + 100;  break; case int b:  data=b++;  break; case string c:  data= c + "aaa";  break; default:  data = null;  break; }

Try to input-1. The result is as follows:

4. ref locals and returns (returns local variables and references)

Completed, please go to: C #7.0 ref locals and returns (return local variables and references)

5. Local Functions (Local function)

Well, this is a little revolutionary. We all know that local variables refer to variables that can only be accessed in a specific process or function.

Then this local function, as the name implies: a function that can be accessed only in a specific function (mother egresses)

The usage is as follows:

Public static void DoSomeing () {// call Dosmeing2 int data = Dosmeing2 (100,200); Console. writeLine (data); // defines the local function, Dosmeing2. int Dosmeing2 (int a, int B) {return a + B ;}}

Er, the explanation is that a DoSomeing2 method is defined in DoSomeing.

(Note: It is worth mentioning that the local function definition can be called within the method at any position of the method, without the need to follow the line-by-line Parsing Method)

6. More expression-bodied members (More function member expression bodies)

In C #6.0, the method body with only one statement can be abbreviated as an expression.

As follows:

Public void CreateCaCheContext () => new CaCheContext (); // equivalent to the following code: public void CreateCaCheContext () {new CaCheContext ();}

However, C #7.0 does not support constructor, destructor, and attribute accessors. The Code is as follows:

// Write the constructor expression public CaCheContext (string label) => this. Label = label; // write the constructor expression ~ CaCheContext () => Console. Error. WriteLine ("Finalized! "); Private string label; // Get/Set attribute accessors Write public string Label {get => label; set => this. label = value ?? "Default label ";}

7. throw Expressions (exception expression)

Before C #7.0, we want to determine whether a string is null. If it is null, an exception is thrown. We need to write this:

Public string IsNull () {string a = null; if (a = null) {throw new Exception ("Exception! ");} Return ;}

In this way, we are very inconvenient, especially in a ternary or non-null expression, we cannot discard this exception and need to write the if statement.

In C #7.0, we can:

Public string IsNull () {string a = null; return ?? Throw new Exception ("Exception! ");}

8. Generalized async return types (general asynchronous return type)

Well, how can I say this? In fact, I am rarely used asynchronously, so I don't have a deep understanding of this feeling. I still feel that it should be useful in some specific situations.

I directly translated the official original text, and the instance code is also the official original text.

The Asynchronous Method must return void, Task, or Task <T>. This time, a new ValueTask <T> is added to prevent the asynchronous running results from being available when they are waiting, assign the Task <T>. For Asynchronous scenarios with Buffer Design in many examples, this can greatly reduce the allocation quantity and significantly improve performance.

The official instance shows two solutions: one data, which can be returned asynchronously or synchronously using ValueTask when the data has been cached.

 public class CaCheContext { public ValueTask<int> CachedFunc() { return (cache) ? new ValueTask<int>(cacheResult) : new ValueTask<int>(loadCache()); } private bool cache = false; private int cacheResult; private async Task<int> loadCache() { // simulate async work: await Task.Delay(5000); cache = true; cacheResult = 100; return cacheResult; } }

The call code and result are as follows:

// The main method cannot be modified Using async, so the delegate is used. static void Main (string [] args) {Action act = async () => {CaCheContext cc = new CaCheContext (); int data = await cc. cachedFunc (); Console. writeLine (data); int data2 = await cc. cachedFunc (); Console. writeLine (data2) ;}; // call the delegate act (); Console. read ();}

The above code is called twice in a row. For the first time, the result is returned within 5 seconds. For the second time, the result is not directly returned, which is consistent with the expected result.

9. Numeric literal syntax improvements (Numeric text syntax improvement)

This is purely for good looks.

In C #7.0, the separator "_" is allowed in numbers to improve readability. For example:

Int a = 123_456; int B = 0xAB_CD_EF; int c = 123456; int d = 0 xABCDEF; Console. writeLine (a = c); Console. writeLine (B = d); // the above Code will display two true values, and the "_" Separator in the number will not affect the result, just to improve readability

Of course, since it is a digital separator, decimal, float, and double can be separated in this way.

The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.

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.