前言
今天咱们一起来探索并实践 C# 12 引入的全新功能!
-
C#/.NET该如何自学入门?
注意:使用这些功能需要使用最新的 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);}
集合表达式
集合表达式引入了一种新的简洁语法,用于创建常用集合值。可以使用展开运算符(..)将其他集合内联到这些值中。
下面的示例展示了集合表达式的用法:
public static void CollectionExpressions(){// 创建一个数组int[] array = [55, 99, 100, 33];// 创建一个列表List<string> list = ["one", "two", "three", "five", "追逐时光者"];// 创建一个 SpanSpan<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]];}
展开运算符(..)示例代码:
展开运算符(集合表达式中的 ..)可将其参数替换为该集合中的元素。 参数必须是集合类型。 以下示例演示了展开运算符的工作原理:
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