C#中AsMemory方法

时间:2024-07-12 19:57:55

1、效率:Memory<T>和Span<T>有助于避免不必要的分配,对频繁操作数组或字符串时起到提高其性能。

2、安全:类型都提供了安全和经过边界检查的内存访问,能降低常见编程错误风险。

3、灵活性:Memory<T>可以存储在堆上并用于异步编程,与仅限于堆栈的Span<T>不同。

// 定义一个数组            string[] weekDays = { "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};            // 从数组中创建Memory<string>            Memory<string> memory = weekDays.AsMemory();            // 创建Memory<string>的一个切片            Memory<string> slice = memory.Slice(3, weekDays.Length-3);            // 访问切片中的元素            foreach (var day in slice.Span)            {                // 输出: Wednesday Thursday Friday Saturday                Console.WriteLine(day);             }

string text = "Create a object.";            // 从字符串创建内存<char>            Memory<char> memory = text.AsMemory().ToArray();            // 创建内存<char>的一个切片            Memory<char> slice = memory.Slice(9, 6);            // 将内存切片转换回字符串            string result = new string(slice.Span);            // 输出: object            Console.WriteLine(result); 

// 定义一个数组            string[] weekDays = { "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" };            // 定义一个新数组            string[] slice = new string[weekDays.Length - 3];            // 将元素从原始数组复制到新数组            Array.Copy(weekDays, 3, slice, 0, weekDays.Length-3);            // 访问新数组中的元素            foreach (var day in slice)            {                // 输出: Wednesday Thursday Friday Saturday                Console.WriteLine(day);             }

 // 定义一个数组            string[] weekDays = { "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" };            // 通过LINQ创建一个数组            string[] slice = weekDays.Skip(3).Take(weekDays.Length-3).ToArray();            // 访问新数组中的元素            foreach (var day in slice)            {                // 输出: Wednesday Thursday Friday Saturday                Console.WriteLine(day);             }