private Dictionary<int, string> webErrors = new Dictionary<int, string>
{[404] = "Page not Found",[302] = "Page moved, but left a forwarding address.",[500] = "The web server can't come out to play today."
};
C#7.x 中新增的功能
1out 變量
可以在方法調(diào)用的參數(shù)列表中聲明 out 變量,而不是編寫單獨的聲明語句::
if (int.TryParse(input, out int result))Console.WriteLine(result);
elseConsole.WriteLine("Could not parse input");
為清晰明了,可能需指定 out 變量的類型,如上所示。 但是,該語言支持使用隱式類型的局部變量:
if (int.TryParse(input, out var answer))Console.WriteLine(answer);
elseConsole.WriteLine("Could not parse input");
public class Example
{public static void Main(){var (_, _, _, pop1, _, pop2) = QueryCityDataForYears("New York City", 1960, 2010);Console.WriteLine($"Population change, 1960 to 2010: {pop2 - pop1:N0}");}private static (string, double, int, int, int, int) QueryCityDataForYears(string name, int year1, int year2){int population1 = 0, population2 = 0;double area = 0;if (name == "New York City"){area = 468.48;if (year1 == 1960){population1 = 7781984;}if (year2 == 2010){population2 = 8175133;}return (name, area, year1, population1, year2, population2);}return ("", 0, 0, 0, 0, 0);}
}
4is 模式匹配
模式匹配支持 is 表達式和 switch 表達式。 每個表達式都允許檢查對象及其屬性以確定該對象是否滿足所尋求的模式。 使用 when 關(guān)鍵字來指定模式的其他規(guī)則:
public static int SumPositiveNumbers(IEnumerable<object> sequence)
{int sum = 0;foreach (var i in sequence){switch (i){case 0:break;case IEnumerable<int> childSequence:{foreach(var item in childSequence)sum += (item > 0) ? item : 0;break;}case int n when n > 0:sum += n;break;case null:throw new NullReferenceException("Null found in sequence");default:throw new InvalidOperationException("Unrecognized type");}}return sum;
}
public static IEnumerable<char> AlphabetSubset3(char start, char end)
{if (start < 'a' || start > 'z')throw new ArgumentOutOfRangeException(paramName: nameof(start), message: "start must be a letter");if (end < 'a' || end > 'z')throw new ArgumentOutOfRangeException(paramName: nameof(end), message: "end must be a letter");if (end <= start)throw new ArgumentException($"{nameof(end)} must be greater than {nameof(start)}");return alphabetSubsetImplementation();IEnumerable<char> alphabetSubsetImplementation(){for (var c = start; c < end; c++)yield return c;}
}
注意上邊的alphabetSubsetImplementation方法,是在內(nèi)部定義的。
同樣可以使用異步:
public Task<string> PerformLongRunningWork(string address, int index, string name)
{if (string.IsNullOrWhiteSpace(address))throw new ArgumentException(message: "An address is required", paramName: nameof(address));if (index < 0)throw new ArgumentOutOfRangeException(paramName: nameof(index), message: "The index must be non-negative");if (string.IsNullOrWhiteSpace(name))throw new ArgumentException(message: "You must supply a name", paramName: nameof(name));return longRunningWorkImplementation();async Task<string> longRunningWorkImplementation(){var interimResult = await FirstWork(address);var secondResult = await SecondStep(index, name);return $"The results are {interimResult} and {secondResult}. Enjoy.";}
}
public const int Sixteen = 0b0001_0000;
public const int ThirtyTwo = 0b0010_0000;
public const int SixtyFour = 0b0100_0000;
public const int OneHundredTwentyEight = 0b1000_0000;
using 聲明是前面帶 using 關(guān)鍵字的變量聲明。 它指示編譯器聲明的變量應(yīng)在封閉范圍的末尾進行處理。 以下面編寫文本文件的代碼為例:
static int WriteLinesToFile(IEnumerable<string> lines)
{using var file = new System.IO.StreamWriter("WriteLines2.txt");// Notice how we declare skippedLines after the using statement.int skippedLines = 0;foreach (string line in lines){if (!line.Contains("Second")){file.WriteLine(line);}else{skippedLines++;}}// Notice how skippedLines is in scope here.return skippedLines;// file is disposed here
}
前面的代碼相當于下面使用經(jīng)典 using 語句的代碼:
static int WriteLinesToFile(IEnumerable<string> lines)
{// We must declare the variable outside of the using block// so that it is in scope to be returned.int skippedLines = 0;using (var file = new System.IO.StreamWriter("WriteLines2.txt")){foreach (string line in lines){if (!line.Contains("Second")){file.WriteLine(line);}else{skippedLines++;}}return skippedLines;} // file is disposed here
}
int M()
{ int y = 5;int x = 7;return Add(x, y);static int Add(int left, int right) => left + right;
}
8async 異步流
從 C# 8.0 開始,可以創(chuàng)建并以異步方式使用流。返回異步流的方法有三個屬性:
它是用 async 修飾符聲明的。
它將返回 IAsyncEnumerable<T>。
該方法包含用于在異步流中返回連續(xù)元素的 yield return 語句。
public static async System.Collections.Generic.IAsyncEnumerable<int> GenerateSequence()
{for (int i = 0; i < 20; i++){await Task.Delay(100);yield return i;}
}await foreach (var number in GenerateSequence())
{Console.WriteLine(number);
}
異步可釋放:
從 C# 8.0 開始,語言支持實現(xiàn) System.IAsyncDisposable 接口的異步可釋放類型。可使用 await using 語句來處理異步可釋放對象。
var now = new WeatherObservation
{ RecordedAt = DateTime.Now, TemperatureInCelsius = 20, PressureInMillibars = 998.0m
};
3頂級語句
頂級語句從許多應(yīng)用程序中刪除了不必要的流程。只有一行代碼執(zhí)行所有操作。 借助頂級語句,可使用 using 語句和執(zhí)行操作的一行替換所有樣本:
using System;Console.WriteLine("Hello World!");
如果需要單行程序,可刪除 using 指令,并使用完全限定的類型名稱:
System.Console.WriteLine("Hello World!");
4模式匹配增強功能
C# 9 包括新的模式匹配改進:
類型模式要求在變量是一種類型時匹配
帶圓括號的模式強制或強調(diào)模式組合的優(yōu)先級
聯(lián)合 and 模式要求兩個模式都匹配
析取 or 模式要求任一模式匹配
求反 not 模式要求模式不匹配
關(guān)系模式要求輸入小于、大于、小于等于或大于等于給定常數(shù)。
public static bool IsLetter(this char c) =>c is >= 'a' and <= 'z' or >= 'A' and <= 'Z';public static bool IsLetterOrSeparator(this char c) =>c is (>= 'a' and <= 'z') or (>= 'A' and <= 'Z') or '.' or ',';
?
5調(diào)試和完成功能
在 C# 9.0 中,已知創(chuàng)建對象的類型時,可在 new 表達式中省略該類型。 最常見的用法是在字段聲明中: