3.引用实例成员中的构造函数参数
public class BankAccount(string accountID, string owner) { public string AccountID { get; } = accountID; public string Owner { get; } = owner; public override string ToString() => $"Account ID: {AccountID}, Owner: {Owner}"; }
// Create an array: int[] a = [1, 2, 3, 4, 5, 6, 7, 8]; // Create a list: List<string> b = ["one", "two", "three"]; // Create a span Span<char> c = ['a', 'b', 'c', 'd', 'e', 'f', 'h', 'i']; // Create a jagged 2D array: int[][] twoD = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]; // Create a jagged 2D array from variables: int[] row0 = [1, 2, 3]; int[] row1 = [4, 5, 6]; int[] row2 = [7, 8, 9]; int[][] twoDFromVariables = [row0, row1, row2];此外,展开运算符(集合表达式中的 ..)可将其参数替换为该集合中的元素,参数必须是集合类型,可以简化多个集合操作的过程。
int[] row0 = [1, 2, 3]; int[] row1 = [4, 5, 6]; int[] row2 = [7, 8, 9]; int[] single = [..row0, ..row1, ..row2]; foreach (var element in single) { Console.Write($"{element}, "); } // output: // 1, 2, 3, 4, 5, 6, 7, 8, 9,
[System.Runtime.CompilerServices.InlineArray(10)] public struct Buffer { private int _element0; } // Usage var buffer = new Buffer(); for (int i = 0; i < 10; i++) buffer[i] = i; foreach (var i in buffer) Console.WriteLine(i);此外,C#12还引入了拦截器和Experimental属性两个试验性功能。用 Experimental 特性标记的程序集或模块中声明的所有类型都是实验性的。 如果访问其中任何一种类型,编译器都会发出警告。 可以禁用这些警告以试用实验性功能。拦截器允许将特定方法调用重新路由到不同的代码,它适用于一些高级场景,特别是允许更好的提前编译(AOT)。
var IncrementBy = (int source, int increment = 1) => source + increment; // 堆代码 duidaima.com Console.WriteLine(IncrementBy(5)); // 6 Console.WriteLine(IncrementBy(5, 2)); // 7
public partial class Form1 : Form { public Form1() { InitializeComponent(); button1.Click += async (sender, e) => { await ExampleMethodAsync(); textBox1.Text += "\r\nControl returned to Click event handler.\n"; }; } private async Task ExampleMethodAsync() { // The following line simulates a task-returning asynchronous process. await Task.Delay(1000); } }2.表达式 lambda
(input-parameters) => expression3.语句 lambda
(input-parameters) => { <sequence-of-statements> }
Func<(int, int, int), (int, int, int)> doubleThem = ns => (2 * ns.Item1, 2 * ns.Item2, 2 * ns.Item3); var numbers = (2, 3, 4); var doubledNumbers = doubleThem(numbers); Console.WriteLine($"The set {numbers} doubled: {doubledNumbers}"); // Output: // The set (2, 3, 4) doubled: (4, 6, 8)