Span and two dimensional Arrays

前端 未结 4 759
轮回少年
轮回少年 2020-12-19 08:16

Is it possible to use the new System.Memory Span struct with two dimensional arrays of data?

double[,] testMulti = 
    {
        { 1, 2, 3, 4 },
        { 5         


        
4条回答
  •  渐次进展
    2020-12-19 09:04

    All spans are one-dimensional because memory is one-dimensional.

    You can of course map all manner of structures onto one-dimensional memory, but the Span class won't do it for you. But you could easily write something yourself, for example:

    public class Span2D where T : struct
    {
        protected readonly Span _span;
        protected readonly int _width;
        protected readonly int _height;
    
        public Span2D(int height, int width)
        {
            T[] array = new T[_height * _width];
            _span = array.AsSpan();
        }
    
        public T this[int row, int column]
        {
            get
            {
                return _span[row * _height + column];
            }
            set
            {
                _span[row * _height + column] = value;
            }
        }
    }
    

    The tricky part is implementing Slice(), since the semantics are sort of ambiguous for a two-dimensional structure. You can probably only slice this sort of structure by one of the dimensions, since slicing it by the other dimension would result in memory that is not contiguous.

提交回复
热议问题