当前位置:网站首页>On the practical application of C 9's new features

On the practical application of C 9's new features

2020-11-09 19:11:01 Dongxie Dugu

You must be curious :“ Old week , Where did you fly the plane ? I haven't blogged for so long .”

Old week :“ I can't afford a plane , Opened an iron mine , A year and a half of digging stones . Who knows that the iron ore has collapsed , Several centipedes were crushed to death , Nothing was dug .”

therefore , Such a loss of the dead , Don't mention it , My grandfather taught me to keep a low profile ……

 

A blink of an eye ,.NET 5 We're going to have , It also brings C# 9. Imagine that , Lao Zhou just got in touch with him .NET 1.1 When , Just went to college ; Now it's over 13 Years. . Time is a fruit knife , Never forgive .

Lao Zhou seldom wrote such as “XXX New characteristics ” Articles like that , I always think it's useless . however , in the light of C# 9, What does Lao Zhou want to say .

good , Before we start , Lao Zhou stressed it again : These are the new features of the language , You must not study on purpose , Do not , Don't , Don't , Say important things four times ! All you have to do is look at the official instructions , You can master it by brushing it once ( It's much more tiktok than brush. ), You don't have to learn . If you have to learn the cost of these things , I just want to say something good to sing but not to hear —— Your ability to learn is really questionable .

 

Okay , Let's start the show .

First out :record type

record , I'll use the original words , I know there is a translation for “ Record type ” That's what I'm saying . It's just , It's just , Lao Zhou thinks this is not very good , But Lao Zhou couldn't find a better word , Or use it back record Well .

record yes Reference type , Follow class It's like ( It's almost ). that , It is familiar to the people class Is it not fragrant , Why add one record Well ? answer : For the convenience of data comparison .

Don't understand ? Don't worry , To look down . Recently, an enthusiastic neighbor sent an old Monday pet :

    public class Cat
    {
        public string Nick { get; set; }
        public string Name { get; set; }
        public int Age { get; set; }
    }

This new pet is not easy , One top one high class food . Fish 、 pork 、 A chicken leg 、 cookies 、 tofu 、 bread 、 Fruits 、 noodles 、 Wheat 、 moth …… Anyway , As long as it's in your mouth , It's all eaten .

Next , We new Two pet examples .

            //  Two examples describe the same cat 
            Cat pet1 = new Cat
            {
                Nick = " Pine nuts ",
                Name = "Jack",
                Age = 1
            };
            Cat pet2 = new Cat
            {
                Nick = " Pine nuts ",
                Name = "Jack",
                Age = 1
            };

            //  It's not the same cat 
            Console.WriteLine(" The same one ?{0}", pet1 == pet2);

Actually , The two examples describe my darling . But , The output is :

 The same one ?False

This is because , In equality comparison , Type references of concern —— Is the reference the same instance . however , In the data processing scheme , We are more concerned with fields in objects / Whether the attributes are equal , Content comparison .

Now? , hold Cat The statement was changed to record type .

    public record Cat
    {
        public string Nick { get; set; }
        public string Name { get; set; }
        public int Age { get; set; }
    }

And then use the same thing on top pet1 and pet2 Examples are compared for equality , Get the expected result :

 The same one ?True

 

record Type saves you from rewriting equality comparisons ( rewrite Equals、GetHashCode Or overloaded operators ) The logic of .

actually , The code is compiled record Type is also a class , But it automatically implements the logic of member equality comparison . What you used to do manually is now left to the compiler .

If , There is one User type , Used to represent user information ( Include user name 、 password ), And then this User Types in data processing schemes may produce N More than one instance . For example, you can start from EF Select one from the model User example A, Based on the login name and password entered by the user User example B. In order to verify that the login information entered by the user is correct , If User yes class, You may have to judge that :

if(A.UserName == B.UserName && A.Password == B.Password)
{
    ..................
}

But if you put User Defined as record type , that , A word of time :

A == B

 

Second out : Pattern matching (Pattern Matching)

" Pattern matching " This translation feels strange , Lao Zhou hasn't come up with any better words . Pattern matching is not something magical , It's just an extended behavior when detecting variable values . before , Old feeling C++/C# Of switch The statement is not strong enough , Because of the traditional usage , Every case Clause can only compare a single constant value . such as

            int  Test results  = 85;

            switch ( Test results )
            {
                case 10:
                    Console.WriteLine(" It's just a little bit of a break in the exam ");
                    break;
                case 50:
                    Console.WriteLine(" It's a little bit close , It's qualified ");
                    break;
                case 85:
                    Console.WriteLine(" It's a show ");
                    break;
                case 90:
                    Console.WriteLine(" Miracles happen ");
                    break;
            }

I fantasized , I wish I could write like this :

            switch ( Test results )
            {
                case 0:
                    Console.WriteLine(" miss an exam ?");
                    break;
                case > 0 && <= 30:
                    Console.WriteLine(" Too bad ");
                    break;
                case > 30 && < 60:
                    Console.WriteLine(" Not yet. ");
                    break;
                case >= 60 && < 80:
                    Console.WriteLine(" We have to work hard ");
                    break;
                case >= 80 && < 90:
                    Console.WriteLine(" Xiuer , Excellent ");
                    break;
                case >= 90 && <= 100:
                    Console.WriteLine(" Pretty good , Miracle ");
                    break;
            }

 

It's been waiting for years and years (“ Wait a thousand years , etc. ……”) in the future , Finally, it can be realized .

            switch ( Test results )
            {
                case 0:
                    Console.WriteLine(" miss an exam ?");
                    break;
                case > 0 and <= 30:
                    Console.WriteLine(" Too bad ");
                    break;
                case > 30 and < 60:
                    Console.WriteLine(" Not yet. ");
                    break;
                case >= 60 and < 80:
                    Console.WriteLine(" We have to work hard ");
                    break;
                case >= 80 and < 90:
                    Console.WriteLine(" Xiuer , Excellent ");
                    break;
                case >= 90 and <= 100:
                    Console.WriteLine(" Pretty good , Miracle ");
                    break;
            }

Yossi , It's delicious .

 

occasionally , Not only do you want to detect the value of the object , It has to go deep into its members . Here's an example ,Order Class represents an order information .

    public class Order
    {
        public int ID { get; set; }
        public string Company { get; set; }
        public string ContactName { get; set; }
        public float Qty { get; set; }
        public decimal UP { get; set; }
        public DateTime Date { get; set; }
    }

Not long ago , The company received a sum of money Order, It should be a good profit .

            Order od = new Order
            {
                ID = 11,
                Company = " Big mouth dog Trading Co., Ltd ",
                ContactName = " Mr. Chen ",
                Qty = 425.12f,
                UP = 1000.55M,
                Date = new(2020, 10, 27)
            };

If I want to be in a variable od Do on switch, have a look , That's it :

            switch (od)
            {
                case { Qty: > 1000f }:
                    Console.WriteLine(" Get rich , Get rich ");
                    break;
                case { Qty: > 500f }:
                    Console.WriteLine(" good heavens , Annual large order ");
                    break;
                case { Qty: > 100f }:
                    Console.WriteLine(" The order volume is good ");
                    break;
            }

Why ? this , What the hell is this ? Don't be surprised , This is not a ghost . It means judgment Qty The value of the property , If the order volume is greater than 100 It outputs “ The order volume is good ”; If the order volume is greater than 1000, Then output “ Get rich , Get rich ”.

But you would say , How did these braces come from ? Remember this LINQ How to write it ?

    from x in ...
        where x.A ...
        select new {
            Prop1 = ...,
            Prop2 = ...,
            ................
        }            

new { ... } Is an anonymous type instance , What if it's a non anonymous type , Look at the front Cat Instance initialization .

     Cat {
         ..........
     }

That's right , This pair of braces is used to construct the member value of an instance , therefore , above switch That's how it's written :

            switch (od)
            {
                case Order{ Qty: > 1000f }:
                    Console.WriteLine(" Get rich , Get rich ");
                    break;
                case Order{ Qty: > 500f }:
                    Console.WriteLine(" good heavens , Annual large order ");
                    break;
                case Order{ Qty: > 100f }:
                    Console.WriteLine(" The order volume is good ");
                    break;
            }

Order{ ... } It's a match Order Object instances , And its Qty The attribute should be consistent with ... Conditions . Because of the variable od It's always been Order type , therefore ,case In Clause Order Just omit , become

                case { Qty: > 1000f }:
                    Console.WriteLine(" Get rich , Get rich ");
                    break;

If multiple attributes appear , Set matching criteria for multiple attributes , Between them is “ And ” The relationship between . such as

                case { Qty: > 100f, Company: not null }:
                    Console.WriteLine(" The order volume is good ");
                    break;

What do you mean ? This is OK “ Wang Wensheng yi” Of ,Qty The value of the property should be greater than 100, also Company The value of property cannot be null. Not for null The way to write is not null, Don't write as !null, Because it's so ugly .

 

If you have fewer branches of code , You can use it. if Of the statement , It's just a matter of cooperation is Operator .

            if (od is { UP: < 3000M })
            {
                Console.WriteLine(" The offer is not ideal ");
            }

however , At present, this writing method has limitations , It can only be judged by constant values , If you write like this, you will report an error .

            if (od is { Date: < DateTime.Now })
            {
                ................
            }

DateTime.Now Not a constant value , The above code cannot be compiled .

 

is Operators were used to match types , The above usage is its grammatical extension .

            object n = 5000000L;
            if(n is long)
            {
                Console.WriteLine(" It's a long integer ");
            }

After evolution is The operator can also be used in this way :

            object n = 5000000L;
            if(n is long x)
            {
                Console.WriteLine(" It's a long integer , The stored values are :{0}", x);
            }

If you are in the if To use the n Value , You can change it to long Type and assign it to a variable x, That's one step , There's no need to write another sentence long x = (long)n .

 

If switch... Statement needs to return a value after judgment , You can also use it as an expression . Let's take the front one Order Change the example .

            string message = od switch
            {
                { Qty: > 1000f }    => " Get rich ",
                { Qty: > 500f }     => " Annual large order ",
                { Qty: > 100f }     => " The order volume is good ",
                _                   => " Unknown "
            };

            Console.WriteLine(message);

You have to pay attention at this time :

1)switch Now it's the expression , Not a statement block , So the semicolon to the right of the final brace cannot be less ;

2) because switch It's an expression , You can't use case Clause , So match directly with specific content ;

3) Finally back to “ Unknown ” That's the underline (_), It's called “ abandoned infant ”, Oh no , yes “ Abandon yuan ”, A variable that is assigned a value but does not need to be used , You can throw it away . This is equivalent to switch In statement block default Clause , When none of the previous conditions match , Just go back to “ Unknown ”.

 

Third out : Attribute init accessor

You have to know first , This init Only used in the initialization phase of read-only properties , For readable and writable properties , Same as before , direct get; set; that will do .

Some people say that int I don't know what to do , Good. , Let's not talk about it yet , First look at it. C# New attribute initialization statements in previous versions .

    public class Dog
    {
        public int No { get; } = 0;
        public string Name { get; } = "no name";
        public int Age { get; } = 1;
    }

You see , This allows you to assign an initial value to the property , That's more init What are you doing ?

good , I'll create a problem for you —— If I initialize like this Dog Attributes of a class , You try .

            Dog x = new Dog
            {
                No = 100,
                Name = " Gigi ",
                Age = 4
            };

Have a try , Does the compilation go wrong .

 

 

There are some cases , You can assign initial values in the property definition phase , But sometimes , You have to initialize it in the code . in the past , We will solve this problem by defining a constructor with parameters .

    public class Dog
    {
        public int No { get; } = 0;
        public string Name { get; } = "no name";
        public int Age { get; } = 1;

        public Dog(int no, string name, int age)
        {
            No = no;
            Name = name;
            Age = age;
        }
    }

then , This initializes .

   Dog x = new(1001, " Gigi ", 4);

 

But , This is still not high enough , You can't do this for every class, can you , It's not hard , But every class has to write a constructor , Not neat .

therefore ,init The accessor works , Let's put Dog Class change .

    public class Dog
    {
        public int No { get; init; }
        public string Name { get; init; }
        public int Age { get; init; }
    }

You don't have to write constructors with parameters anymore , Instance, the property is assigned directly .

            Dog x = new Dog
            {
                No = 100,
                Name = " Gigi ",
                Age = 4
            };

thus , These read-only properties have default initial values .

Of course , This assignment is only valid during initialization , After initialization, you want to change the value of the property , No way !

            x.Name = " Winter and winter ";  // error 
            x.Age = 10;       // error 

 

Um. , Okay , That's Lao Zhou, right C# 9 Some unwritten statements about the use of new features . Don't say it's difficult after you've read it .

 

版权声明
本文为[Dongxie Dugu]所创,转载请带上原文链接,感谢