publicvoidAppendFormatted<T>(T value, string format) where T : IFormattable { _builder.Append(value?.ToString(format, null)); Console.WriteLine($"Appended formatted with format: {value} with format {format}"); }
publicvoidAppendFormatted(stringvalue, int alignment) { _builder.Append(value.PadRight(alignment)); Console.WriteLine($"Appended formatted string with alignment: {value} with alignment {alignment}"); }
publicvoidAppendFormatted<T>(T value, int alignment) where T : IFormattable { _builder.Append(value?.ToString()?.PadRight(alignment)); Console.WriteLine($"Appended formatted with alignment: {value} with alignment {alignment}"); }
publicvoidAppendFormatted<T>(T value, int alignment, string format) where T : IFormattable { _builder.Append(value?.ToString(format, null)?.PadRight(alignment)); Console.WriteLine($"Appended formatted with alignment and format: {value} with alignment {alignment} and format {format}"); }
用 global using 語法來讓整個專案預設引入常用命名空間,減少單一個 *.cs 檔案中的 using。
如果有使用夠完善的 IDE 下看起來弊大於利,方便沒多少但容易衍生更多的維護成本,全域的命名空間和各檔案間命名空間下同名類別混淆的情況會更難排查,要避免的話全域的 using 還得經過嚴謹的設計、規範與程式碼審查制度,會增加不少維護成本。
檔案範圍的命名空間宣告 (File-scoped namespace declaration)
就省掉一個縮排而已。
1 2 3 4 5 6 7 8 9 10 11 12 13
// Just save 1 indention namespaceMyNamespace;
classA { // .... }
classB { // .... }
初步看來是個幫助很小的功能,預設有套用就用,沒套用的話也沒必要刻意去改。
擴充屬性在模式比對時的模式 (Extended property patterns)
1 2 3 4 5 6 7 8 9 10
// before if (person is { Address: { City: "Springfield" } }) { //... } // after if (person is { Address.City: "Springfield" } }) { //... }
Lambda 運算式改善 (Lambda expression improvements)
編譯器可以從 Lambda 運算式或方法群組推斷委派類型,例如:var add = (int x, int y) => x + y; 可以使用推斷型別 var。
如果無法推論型別則要自己定義。
Attribute 可以加在 Lambda 運算式上。
這讓 Lambda 運算式更像一個方法。
常數差補字串 (Constant interpolated strings)
如果字串插補的元素都是常數,則字串插補的結果可為常數,在編譯期確定字串內容來提升效能和安全性。
1 2 3 4
conststring firstName = "John"; conststring lastName = "Doe"; // Both firstName and lastName are constant, so fullName can be constant. conststring fullName = $"{firstName}{lastName}";
Record 的 ToString 方法可禁止繼承 (Record types can seal ToString)