C#8.0新特性

只讀成員

        private struct Point
        {
            public Point(double x, double y)
            {
                X = x;
                Y = y;
            }

            private double X { get; set; }
            private double Y { get; set; }
            private readonly double Distance => Math.Sqrt(X * X + Y * Y);

            public override readonly string ToString() =>
                $"({X}, {Y}) is {Distance} from the origin";
        }
View Code

使用readonly修飾tostring方法,表示它不可修改異步

默認接口方法

        /// <summary>
        /// 默認接口方法
        /// </summary>
        private interface IWork
        {
            public void Work()
            {
                Console.WriteLine("Work");
            }
        }

如今能夠在接口中定義默認的方法,而不是隻能申明void Work();async

更多的模式匹配

使用switch表達式的模式匹配

            public enum Rainbow
            {
                Red,
                Orange,
                Yellow,
                Green,
                Blue,
                Indigo,
                Violet
            }

            //switch表達式
            public static Color FromRainbow(Rainbow colorBand) =>
                colorBand switch
                {
                    Rainbow.Red => Color.Red,
                    Rainbow.Orange => Color.Orange,
                    Rainbow.Yellow => Color.Yellow,
                    Rainbow.Green => Color.Green,
                    Rainbow.Blue => Color.Blue,
                    Rainbow.Indigo => Color.Indigo,
                    Rainbow.Violet => Color.Violet,
                    _ => throw new ArgumentException(message: "invalid enum value", paramName: nameof(colorBand)),
                };
View Code

在變量後面使用switch關鍵字,同時將case:替換爲=>,使用_替代defaultide

屬性模式

            public static decimal ComputeSalesTax(Address location, decimal salePrice) =>
                location switch
                {
                    { State: "WA" } => salePrice * 0.06M,
                    { State: "MN" } => salePrice * 0.075M,
                    { State: "MI" } => salePrice * 0.05M,
                    // other cases removed for brevity...
                    _ => 0M
                };

            public struct Address
            {
                public string State { get; set; }
            }
View Code

對location變量的State屬性進行模式匹配函數

元組模式

            public static string RockPaperScissors(string first, string second)
                => (first, second) switch
                {
                    ("rock", "paper") => "rock is covered by paper. Paper wins.",
                    ("rock", "scissors") => "rock breaks scissors. Rock wins.",
                    ("paper", "rock") => "paper covers rock. Paper wins.",
                    ("paper", "scissors") => "paper is cut by scissors. Scissors wins.",
                    ("scissors", "rock") => "scissors is broken by rock. Rock wins.",
                    ("scissors", "paper") => "scissors cuts paper. Scissors wins.",
                    (_, _) => "tie"
                };
View Code

位置模式

            //位置模式,使用解構將屬性解構的離散變量,若是能夠訪問 Deconstruct 方法,就可使用位置模式 檢查對象的屬性並將這些屬性用於模式
            public class XPoint
            {
                public int X { get; set; }
                public int Y { get; set; }

                public void Deconstruct(out int x, out int y)
                {
                    x = X;
                    y = Y;
                }
            }

            public int GetNumber(XPoint point) => point switch
            {
                (0, 0) => 0,
                var (x, y) when x > 0 && y > 0 => 1,
                var (x, y) when x < 0 && y > 0 => 2,
                var (x, y) when x < 0 && y < 0 => 3,
                var (x, y) when x > 0 && y < 0 => 4,
                var (_, _) => -1,
                _ => -2
            };
View Code

 using申明

        /// <summary>
        /// using 聲明,using 表達式的操做數能夠實現 IDisposable 或 IAsyncDisposable
        /// </summary>
        public void UsingStatement()
        {
            using var file = new System.IO.StreamWriter("WriteLines2.txt");
        }

能夠對異步可釋放類型使用using關鍵字進行釋放ui

靜態本地函數

        /// <summary>
        /// 靜態本地函數,在本地函數中使用static關鍵字
        /// </summary>
        private class StaticLocalFunction
        {
            int N()
            {
                int y;
                LocalFunction();
                return y;

                void LocalFunction() => y = 0;
            }

            int M()
            {
                int y = 5;
                int x = 7;
                return Add(x, y);

                static int Add(int left, int right) => left + right;
            }
        }
View Code

能夠在本地函數申明中使用static關鍵字spa

索引和範圍

        private class IndexRange
        {
            string[] words = new string[]
            {
                // index from start    index from end
                "The",      // 0                   ^9
                "quick",    // 1                   ^8
                "brown",    // 2                   ^7
                "fox",      // 3                   ^6
                "jumped",   // 4                   ^5
                "over",     // 5                   ^4
                "the",      // 6                   ^3
                "lazy",     // 7                   ^2
                "dog"       // 8                   ^1
            };              // 9 (or words.Length) ^0

            void Test()
            {
                //>=index_1 && < index_4
                var quickBrownFox = words[1..4];
                var lazyDog = words[^2..^0];
            }
        }
View Code

null合併賦值

        /// <summary>
        /// null合併賦值
        /// </summary>
        private void NullMergeAssignment()
        {
            List<int> list = new List<int>();
            List<int> numbers = list.Where(x => x > 20).ToList();
            
            numbers ??= new List<int>();
        }

當左操做數計算爲 null 時,將??= 右操做數的值分配給左操做數code

異步流

public static class AsyncStream
        {
            public static async System.Collections.Generic.IAsyncEnumerable<int> GenerateSequence()
            {
                for (int i = 0; i < 20; i++)
                {
                    await Task.Delay(100);
                    yield return i;
                }
            }


            public static async void GetNumbers()
            {
                var c = CSharp8.AsyncStream.GenerateSequence();
                await foreach (var number in c)
                {
                    Console.WriteLine(number);
                }
            }
        }
View Code

GetNumbers使用await等待返回結果,每隔100ms會輸出i++的值對象

相關文章
相關標籤/搜索