關于 C# 12 新增功能實操!
今天咱們一起來探索并實踐 C# 12 引入的全新功能!
注意:使用這些功能需要使用最新的 Visual Studio 2022 版本或安裝 .NET 8 SDK 。
主構造函數
主構造函數允許你直接在類定義中聲明構造函數參數,并自動生成相應的屬性。
主構造函數參數的最常見用途包括:
- 作為 base() 構造函數調用的參數。
- 初始化成員字段或屬性。
- 引用實例成員中的構造函數參數。
代碼示例
將任何參數放在類型名稱后面的括號中:
public class CSharp12GrammarExercise
{
public static void OutputPrint()
{
var person = new Person("追逐時光者", 30);
Console.WriteLine($"{person.Name}, {person.Age}");
}
}
public class Person(string name, int age)
{
public string Name => name;
public int Age => age;
}
以下代碼初始化從主構造函數參數計算的兩個只讀屬性:
public class CSharp12GrammarExercise
{
public static void OutputPrint()
{
// 創建 Distance 結構體實例
Distance distance = new Distance(10, 55);
// 訪問 Magnitude 和 Direction 屬性
Console.WriteLine($"Magnitude: {distance.Magnitude},Direction: {distance.Direction}");
}
}
public readonly struct Distance(double dx, double dy)
{
public readonly double Magnitude { get; } = Math.Sqrt(dx * dx + dy * dy);
public readonly double Direction { get; } = Math.Atan2(dy, dx);
}
集合表達式
集合表達式引入了一種新的簡潔語法,用于創建常用集合值。可以使用展開運算符(..)將其他集合內聯到這些值中。
(1) 下面的示例展示了集合表達式的用法:
public static void CollectionExpressions()
{
// 創建一個數組
int[] array = [55, 99, 100, 33];
// 創建一個列表
List<string> list = ["one", "two", "three", "five", "追逐時光者"];
// 創建一個 Span
Span<char> span = ['a', 'b', 'c', 'd', 'e', 'f', 'h', 'i', 'k'];
// 創建一個交錯二維數組
int[][] two2D = [[1, 2, 3], [4, 5, 6], [7, 8, 9], [88, 8, 9]];
}
(2) 展開運算符(..)示例代碼:
展開運算符(集合表達式中的 ..)可將其參數替換為該集合中的元素。 參數必須是集合類型。 以下示例演示了展開運算符的工作原理:
int[] item0 = [88, 2, 3];
int[] item1 = [22, 5, 6];
int[] item2 = [7, 99, 9];
int[] totalList = [.. item0, .. item1, .. item2];
foreach (var element in totalList)
{
Console.Write($"{element}, ");
}
沒有.. 會有異常:
正常輸出:
內聯數組
內聯數組用于提高應用程序性能,允許在結構體中創建固定大小的數組。雖然你可能不會自己聲明內聯數組,但當它們通過 System.Span<T> 或 System.ReadOnlySpan<T> 從運行時 API 暴露出來時,你可以透明地使用它們。內聯數組提供與不安全固定大小緩沖區類似的性能特性。
內聯數組的聲明與下面的結構類似:
[System.Runtime.CompilerServices.InlineArray(20)]
public struct Buffer
{
private int _element0;
}
你可以像使用其他數組一樣使用它們:
public static void InlineArrays()
{
var buffer = new Buffer();
for (int i = 0; i < 20; i++)
{
buffer[i] = i;
}
foreach (var i in buffer)
{
Console.WriteLine(i);
}
}
默認 lambda 參數
現在可以為 Lambda 表達式的參數定義默認值,語法和規則與將參數的默認值添加到任何方法或本地函數相同。
如果 lambda 表達式只有一個輸入參數,則括號是可選的:
Func<double, double> testcube = x => x * x * x;
兩個或更多輸入參數使用逗號加以分隔:
Func<int, int, bool> testForEquality = (x, y) => x == y;
可以顯式指定類型,如下面的示例所示:
注意:輸入參數類型必須全部為顯式或全部為隱式;否則,便會生成 CS0748 編譯器錯誤!!
Func<int, string, bool> isTooLong = (int x, string s) => s.Length > x;
任何類型的別名
可以使用 using 別名指令創建任何類型的別名,而不僅僅是命名類型。也就是說,你可以為元組類型、數組類型、指針類型或其他不安全類型創建語義別名。
使用 using 關鍵字為元組類型創建別名,并進行調用:
using PointTest = (int item1, int item2);
namespace HelloDotNetGuide.CSharp語法
{
public class CSharp12GrammarExercise
{
public static void OutputPrint()
{
//使用 using 關鍵字為元組類型創建別名,并進行調用:
PointTest point = (10, 20);
Console.WriteLine($"輸出:Item1={point.Item1}, Item2={point.Item2}");
}
}
}
參考文章
- 詳細功能介紹請閱讀微軟官方文檔:https://learn.microsoft.com/zh-cn/dotnet/csharp/whats-new/csharp-12
- 文章示例源碼地址:https://github.com/YSGStudyHards/DotNetGuide/blob/main/DotNetGuidePractice/HelloDotNetGuide/CSharp%E8%AF%AD%E6%B3%95/CSharp12GrammarExercise.cs