范围运算符和跨度之间的区别

问题描述 投票:0回答:1

考虑这个计划

using System;

namespace ConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            byte[] array = { 1, 2, 3, 4 };
            Span<byte> span = array;
            byte[] dest = new byte[4];
            //span.CopyTo(dest);  // ok
            span.CopyTo(dest[..]);  // NO
            //span.CopyTo(dest.AsSpan());  // ok
            //span.CopyTo(dest.AsSpan()[..]);  // ok

            Console.Out.Write(BitConverter.ToString(dest));
        }
    }
}

在我预期的//NO行上

01-02-03-04

但是得到了

00-00-00-00

发生什么事了?

c# html range slice
1个回答
0
投票

dest[..]
创建一个新数组。所以它有点像这段代码:

byte[] dest = new byte[4];

// This is what the range operator is doing
byte[] actualDest = new byte[4];
dest.CopyTo(actualDest);

// dest and actualDest are separate arrays now,
// so this doesn't affect the content of dest at all
span.CopyTo(actualDest);
© www.soinside.com 2019 - 2024. All rights reserved.