Span复习

Span复习

using System;

namespace Span复习
{
    class Program
    {
        static void Main(string[] args)
        {
            //Console.WriteLine("Hello World!");
            //IntroSpans();
            //var span1 = IntroSpans();

            //CreatSlices(span1);

            int[] int1 = {3,5,2,6,4,5,2,4,6,8,};
            int[] int2 = {5,7,2,3,6,9,3};
            var span1 = new Span<int>(int1);
            var span2 = new Span<int>(int2);
            ChangeValues(span1,span2);
        }

        //使用Span<T>,可以直接访问数组元素。数组的元素没有复制,但是它们可以直接使用,这比复制要快。
        private static Span<int> IntroSpans()
        {
            int[] arr1 = new int[] {1,4,5,11,13,18};
            var span1 = new Span<int>(arr1);
            span1[1] = 11;
            System.Console.WriteLine($"arr1[1] is changed via span[1]: {arr1[1]}");
            System.Console.WriteLine($"span1[1]: {span1[1]}");
            return span1;

        }

        //创建切片
        private static void CreatSlices(Span<int> span1)
        {
            System.Console.WriteLine(nameof(CreatSlices));
            int[] arr2 = {3,5,7,9,11,13,15};
            //var span2 = new Span<int>(arr2);
            var span3 = new Span<int>(arr2,start:3,length:3);
            var span4 = span1.Slice(start:2,length:4);

            DisplaySpan("Content of span3:",span3);
            DisplaySpan("Content of span4:" ,span4);
            System.Console.WriteLine();
        


        }

        //DisplaySpan()用于显示Span的内容
        private static void DisplaySpan(string title,ReadOnlySpan<int> span)
        {
            System.Console.WriteLine(title);
            for(int i = 0;i<span.Length;i++)
            {
                System.Console.Write($"{span[i]} ");

            }
            System.Console.WriteLine();

        }

        //使用Span改变值
        private static void ChangeValues(Span<int> span1,Span<int> span2)
        {
            System.Console.WriteLine(nameof(ChangeValues));
            var span4 = span1.Slice(start:4);
            span4.Clear();//清除了span1从第5位开始后面的数,并用数0填充
            DisplaySpan("content of span1",span1);
            var span5 = span2.Slice(start:3,length:3);
            span5.Fill(42);//span2从第4位开始的三位,用数42来填充
            DisplaySpan("content of span2",span2);
            span5.CopyTo(span1);
            DisplaySpan("content of span1",span1);
            if(!span1.TryCopyTo(span4))
            {
                System.Console.WriteLine("Couldn't copy span1 to span4 because span4 is to small ");
                System.Console.WriteLine($"length of span1: {span1.Length},length of span4: {span4.Length} ");

            }
            System.Console.WriteLine();

        }
    }
}

 

使用Span改变值事例输出如下

ChangeValues
content of span1
3 5 2 6 0 0 0 0 0 0
content of span2
5 7 2 42 42 42 3
content of span1
42 42 42 6 0 0 0 0 0 0
Couldn't copy span1 to span4 because span4 is to small
length of span1: 10,length of span4: 6

 

posted @ 2019-11-26 17:18  singhwong  阅读(134)  评论(0编辑  收藏  举报