public static string MatchComplexPattern(List<int> numbers) { return numbers switch { // 堆代码 duidaima.com [0, .., > 5] => "Starts with 0 and ends with a number greater than 5", [1, 2, 3, .. var rest] when rest.Contains(4) => "Starts with 1, 2, 3 and contains a 4 in the remaining list", _ => "No match found" }; }解释:
[1, 2, 3, .. var rest] 解构列表,检查是否以 1, 2, 3 开头并在剩余部分包含 4。
public interface ICalculable<T> where T : ICalculable<T> { static abstract T Add(T a, T b); static abstract T Subtract(T a, T b); } public struct ComplexNumber : ICalculable<ComplexNumber> { public double Real { get; } public double Imaginary { get; } public ComplexNumber(double real, double imaginary) => (Real, Imaginary) = (real, imaginary); public static ComplexNumber Add(ComplexNumber a, ComplexNumber b) => new ComplexNumber(a.Real + b.Real, a.Imaginary + b.Imaginary); public static ComplexNumber Subtract(ComplexNumber a, ComplexNumber b) => new ComplexNumber(a.Real - b.Real, a.Imaginary - b.Imaginary); }关键点:
ComplexNumber 类型实现了这些操作,从而支持对复数的泛型计算。
using System.Collections.Immutable; var numbers = ImmutableArray.CreateRange(Enumerable.Range(1, 1000000)); // 使用并行处理计算平方数 var squares = numbers.AsParallel().Select(x => x * x).ToImmutableArray(); // 输出前十个平方数 Console.WriteLine(string.Join(", ", squares.Take(10)));效果:
[AttributeUsage(AttributeTargets.Class, Inherited = false)] public sealed class AutoDtoAttribute : Attribute { } public class AutoDtoGenerator : ISourceGenerator { public void Initialize(GeneratorInitializationContext context) { } public void Execute(GeneratorExecutionContext context) { // 找到标记 [AutoDto] 的类并注入成员 } }优势:
自动生成 Equals、ToString 等通用成员,提高代码一致性,降低维护成本。
public static async IAsyncEnumerable<string?> FetchDataAsync(string apiUrlAddress) { using var httpClient = new HttpClient(); using var response = await httpClient.GetAsync(apiUrlAddress, HttpCompletionOption.ResponseHeadersRead); response.EnsureSuccessStatusCode(); using var stream = await response.Content.ReadAsStreamAsync(); using var reader = new StreamReader(stream); while (!reader.EndOfStream) { yield return await reader.ReadLineAsync(); } } public static async Task ProcessDataAsync(string apiUrlAddress) { await foreach (var line in FetchDataAsync(apiUrlAddress)) { Console.WriteLine(line); } }优势:
<PropertyGroup> <PublishAot>true</PublishAot> </PropertyGroup>通过以下命令发布应用程序:
dotnet publish -c Release -r win-x64 --self-contained总结