[Dry goods to attack] c#7.0 new Features (VS2017 available)

Source: Internet
Author: User
Tags define local

Original: http://www.cnblogs.com/GuZhenYin/p/6526041.html

Objective

Microsoft released the new vs 2017 yesterday. And then there's a lot of stuff .... NET new version of ASP. NET new version ... Wait a minute.. Too many. Not really digested.

Share in fact the December 2016 has been announced the new features of the c#7.0, although very early out, but we do not support the IDE AH.

But in yesterday's VS2017 has been perfectly able to support the use of.

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

First, make a list of the relevant syntax:

1.out-variables (out variable)

2.Tuples (tuple)

3.Pattern Matching (matching mode)

4.refLocals and returns (local variables and references returned)

5.Local Functions (local function)

6.More expression-bodied members (more expression body for a function member)

7.throwExpressions (Exception-expression)

8.Generalized Async return Types ( Universal asynchronous return type)

9.Numeric literal syntax Improvements ( numeric text syntax improvements)

Body 1. Out-variables (out variable)

Previously, when we used an out variable, we needed to declare it externally before we could pass in the method, similar to the following:

String ddd = ""; Declare the variable CCC first. Stringout (out DDD); Console.WriteLine (DDD);

In c#7.0 we may not have to declare it directly at the time of argument passing, as follows:

Stringout (out string ddd); Delivery of the same time affirm Console.WriteLine (DDD); Console.ReadLine ();

2.Tuples (tuple)

Roost in. In NET4.0, Microsoft gave us a solution called tuples for multiple return values, similar to the following code:

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 above code shows a method that returns a tuple with 3 strings, but when we get to the value, the heart has blown up when we use it, and Item1,item2,item3 is a ghost, though it has reached our request, but it is not elegant.

So, in c#7.0, Microsoft offers a more elegant solution: (Note: the need to refer to System.valuetuple via NuGet ) is as follows:

        static void Main (string[] args)        {            var data=getfullname ();            Console.WriteLine (DATA.A); The available name gets to the value            Console.WriteLine (data.b);            Console.WriteLine (DATA.C);            Console.ReadLine ();        }        The A,string method is defined as multiple return values and named        private static (string b,string C) getfullname ()        {            return ("A", "B", "C");        }

Deconstruct tuples, sometimes we do not want to use Var anonymous to obtain, then how to get ABC? We can be as follows:

static void Main (string[] args)        {           //defines a destructor tuple            (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, a matching pattern was introduced, and an old chestnut was first raised. An object type, we want to determine whether he is int if it is int we add 10, then output, need the following:

Object A = 1;if (A is int)//is judgment {  int b = (int) A;//split  int d = b+10;//+  Console.WriteLine (d);//Output}

So in c#7.0, the first is a small extension of is, we just need to write this, as follows:

Object A = 1;if (A is int c)//Here, the value of int is directly assigned to c{  int d = c + Ten;  Console.WriteLine (d);}

Is this very convenient? Especially the comrades who often use reflection.

So the question comes, excavator technology which strong?! (cough, yuck jokes)

In fact, if there are multiple types that need to be matched, what do you do? Multiple if else? Of course, but Microsoft's dad also offersswitch的新玩法,我们来看看,如下:

We define an Add method that returns the dynamic type as an object parameter.

        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 below, passing in int type:

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

Output:

We pass in the arguments of type string, and the code and output are as follows:

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

By using the code above, we can realize how smooth and powerful the switch's new gameplay is.

Case-when filtering for matching patterns

Some of the friends will ask. Since we can match the type in switch, can we filter the value by the way? The answer is of course yes.

Let's change the switch code above, as follows:

            Switch (a)            {case                int b when b < 0:                    data = b + +;                    break;                case int B:                    data=b++;                    break;                Case String C:                    data= C + "AAA";                    break;                Default:                    data = null;                    break;            }

In the incoming-1 try, see the results as follows:

4.ref Locals and returns ( Local Variables and the reference return)

Already made up, please visit: http://www.cnblogs.com/GuZhenYin/p/6531814.html

5.Local Functions (local function)

Well, this is a little subversive. As you all know, a local variable refers to a variable that is accessible only in a particular procedure or function.

The local function , as the name implies: a function that can be accessed only in a particular function (the Mother egg is good for the mouth)

Here's how to use it:

       public static void Dosomeing ()        {            //call Dosmeing2            int data = DOSMEING2 (+);            Console.WriteLine (data);            Define local functions, Dosmeing2.            int Dosmeing2 (int a, int b)            {               return a + b;            }        }

Well, the explanation is probably a DoSomeing2 method defined in Dosomeing,.. Called a bit earlier. (Note: It is worth mentioning that the local function definition can be called anywhere in the method, without following the method of progressive parsing)

6.More expression-bodied members (more expression body for a function member)

In c#6.0, a method body that has only one statement can be simply written as an expression.

As follows:

        public void createcachecontext () = new Cachecontext ();        Equivalent to the following code public        void Createcachecontext ()        {            new Cachecontext ();        

However, it is not supported for constructors, destructors, and property accessors, so c#7.0 supports the. The code is as follows:

The expression for the constructor is public cachecontext (string label) and this. Label = label;//The expression of the destructor ~cachecontext () = Console.Error.WriteLine ("finalized!"); private string label;//get/set the expression of the property accessor is the public string label{    Get = = label;    Set = = This.label = value?? "Default label";}
7.throwExpressions (Exception-expression)

Before c#7.0, we wanted to determine if a string was null, and if it was null, we would need to write the exception:

        public string IsNull ()        {            string a = null;            if (a = = null)            {                throw new Exception ("Abnormal!");            }            return A;        }

In this way, we are very inconvenient, especially in ternary or non-empty expressions, can not be thrown out of this exception, the need to write an if statement.

So we can do this in c#7.0:

        public string IsNull ()        {            string a = null;            Return a?? throw new Exception ("Abnormal!");        }

8.Generalized Async return Types (Universal Asynchronous return type)

Well, this, how to say, in fact, I use less asynchronous, so it is not deep understanding of the feeling, still feel the egg, in certain circumstances should be useful.

I directly translated the official text, the example code is the official text.

The Async method must return Void,task or TASK<T>, and this time a new valuetask<t> is added to prevent the results of the asynchronous run from being allocated to task<t> in situations where it is already available. For many examples of asynchronous scenarios designed for buffering, this can significantly reduce the number of allocations and significantly improve performance.

The official example shows the main meaning: a data, in the case of a cache, can use Valuetask to return asynchronous or synchronous 2 kinds of scenarios

    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 (;            cache = true;            Cacheresult = +;            return cacheresult;        }    }

The code and results of the call are as follows:

        The Main method cannot be modified with 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);            };            Invoke delegate              Act ();            Console.read ();        }

The above code, we call 2 consecutive times, the first time, waiting for 5 seconds to appear the result. The second time does not wait for the result to appear directly and the expected effect is consistent.

9.Numeric literal Syntax Improvements (numeric text syntax improvements)

This is purely a. For a good look.

In c#7.0, the "_" symbol is allowed to appear in the number. To improve readability, for example:

            int a = 123_456;            int b = 0xab_cd_ef;            int c = 123456;            int d = 0xABCDEF;            Console.WriteLine (a==c);            Console.WriteLine (B==d);            If the code above shows two true, the "_" delimiter in the number will not affect the result, just to improve readability   

Of course, since it is a number type delimiter, then decimal , float anddouble  都是可以这样被分割的..

[Dry goods to attack] c#7.0 new Features (VS2017 available)

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.