C#中使用Span操作多维数组的完全指南
多维数组与Span的技术深度解析
在C#编程中,处理多维数组是一项常见需求。当我们需要高性能地访问这些数组时,Span
理解多维数组的内存布局
与交错数组(double[][])不同,double[,]这样的多维数组采用矩形结构,且在内存中是连续存储的。C#使用行优先存储策略,意味着数组的第一行元素全部存储完毕后,才会开始存储第二行。
double[,] numbers = new double[3, 4] {
{ 1.0, 2.0, 3.0, 4.0 },
{ 5.0, 6.0, 7.0, 8.0 },
{ 9.0, 10.0, 11.0, 12.0 }
};
// 实际内存布局:1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0
使用MemoryMarshal创建Span视图
从.NET Core 3.0开始,我们可以利用MemoryMarshal.GetArrayDataReference方法获取数组的内部引用,从而创建Span而无需使用fixed语句。这种方法利用了多维数组连续存储的特性。
using System;
using System.Runtime.InteropServices;
public class SpanMatrixDemo
{
public void AccessMultiDimensionalArray()
{
double[,] grid = new double[5, 8];
// 获取数组数据的内部引用
ref double startRef = ref MemoryMarshal.GetArrayDataReference(grid);
// 创建扁平化的Span视图
Span<double> linearView = MemoryMarshal.CreateSpan(ref startRef, grid.Length);
// 以一维方式遍历访问
for (int idx = 0; idx < linearView.Length; idx++)
{
linearView[idx] = Math.Sqrt(idx);
}
Console.WriteLine($"grid[2,3] = {grid[2, 3]}"); // 输出索引19的平方根
}
}
手动索引转换策略
由于Span是一维数据结构,我们需要将二维坐标转换为一维索引。转换公式为:index = rowIndex * columnCount + columnIndex。
public class IndexConverter
{
public void ProcessWithManualCalculation()
{
int[,] values = new int[7, 10];
int rowCount = values.GetLength(0);
int columnCount = values.GetLength(1);
ref int dataRef = ref MemoryMarshal.GetArrayDataReference(values);
Span<int> flatSpan = MemoryMarshal.CreateSpan(ref dataRef, values.Length);
// 手动计算索引进行赋值
for (int r = 0; r < rowCount; r++)
{
for (int c = 0; c < columnCount; c++)
{
int flatIndex = r * columnCount + c;
flatSpan[flatIndex] = r + c;
}
}
// 验证数据
Console.WriteLine($"values[3,5] = {values[3, 5]}"); // 输出 8
}
}
封装更安全的访问方式
直接操作Span的索引计算容易出错,我们可以创建一个包装结构来提供更直观的二维访问语法。
public ref struct GridView<T> where T : unmanaged
{
private readonly Span<T> _buffer;
private readonly int _width;
private readonly int _height;
public GridView(T[,] source)
{
_width = source.GetLength(1);
_height = source.GetLength(0);
_buffer = MemoryMarshal.CreateSpan(ref source[0, 0], source.Length);
}
public ref T this[int row, int col]
{
get
{
ValidateBounds(row, col);
return ref _buffer[row * _width + col];
}
}
private void ValidateBounds(int row, int col)
{
if (row < 0 || row >= _height || col < 0 || col >= _width)
throw new ArgumentOutOfRangeException("索引超出范围");
}
public int Width => _width;
public int Height => _height;
public Span<T> AsFlatSpan() => _buffer;
}
使用这个封装类,我们可以像使用原生二维数组一样访问元素:
public class GridViewUsage
{
public void DemonstrateUsage()
{
double[,] temperatureData = new double[100, 50];
var grid = new GridView<double>(temperatureData);
// 直接使用二维索引
for (int i = 0; i < grid.Height; i++)
{
for (int j = 0; j < grid.Width; j++)
{
grid[i, j] = Math.Sin(i * 0.05) * Math.Cos(j * 0.03);
}
}
// 需要批量处理时获取扁平视图
Span<double> allData = grid.AsFlatSpan();
double sum = 0;
foreach (var value in allData)
{
sum += value;
}
}
}
fixed语句的传统方法对比
在较旧的.NET版本或需要极致性能时,我们可以使用fixed语句配合指针操作:
public unsafe class PointerBasedAccess
{
public void TraditionalApproach(double[,] matrix)
{
int rows = matrix.GetLength(0);
int cols = matrix.GetLength(1);
fixed (double* matrixPtr = &matrix[0, 0])
{
for (int i = 0; i < rows; i++)
{
double* rowStart = matrixPtr + (i * cols);
for (int j = 0; j < cols; j++)
{
rowStart[j] = Compute(i, j);
}
}
}
}
private static double Compute(int x, int y)
{
return Math.Pow(x, 2) + Math.Pow(y, 2);
}
}
虽然指针方法性能相近,但Span版本提供了更好的安全性和可读性,且不需要unsafe上下文。
处理更高维度数组
同样的技术可以扩展到三维甚至更高维度的数组:
public ref struct VolumeView<T> where T : unmanaged
{
private readonly Span<T> _data;
private readonly int _dimX, _dimY, _dimZ;
public VolumeView(T[,,] volume)
{
_dimX = volume.GetLength(0);
_dimY = volume.GetLength(1);
_dimZ = volume.GetLength(2);
_data = MemoryMarshal.CreateSpan(ref volume[0, 0, 0], volume.Length);
}
public ref T this[int x, int y, int z]
{
get
{
int index = (x * _dimY * _dimZ) + (y * _dimZ) + z;
return ref _data[index];
}
}
public int SizeX => _dimX;
public int SizeY => _dimY;
public int SizeZ => _dimZ;
}
// 使用示例
public void Process3DVolume()
{
double[,,] mriScan = new double[256, 256, 128];
var volume = new VolumeView<double>(mriScan);
volume[100, 128, 64] = 1.5;
// 进行某个层面的处理
for (int y = 0; y < volume.SizeY; y++)
{
for (int z = 0; z < volume.SizeZ; z++)
{
volume[50, y, z] *= 1.2;
}
}
}
扩展方法简化使用
为了进一步简化操作,我们可以创建一组扩展方法:
public static class ArrayExtensions
{
public static Span<T> Flatten<T>(this T[,] array) where T : unmanaged
{
ArgumentNullException.ThrowIfNull(array);
return MemoryMarshal.CreateSpan(ref array[0, 0], array.Length);
}
public static int ComputeIndex<T>(this T[,] array, int row, int col)
{
return row * array.GetLength(1) + col;
}
public static GridView<T> AsGrid<T>(this T[,] array) where T : unmanaged
{
return new GridView<T>(array);
}
}
使用这些扩展方法,代码变得更加简洁:
public void UsingExtensions()
{
int[,] numbers = new int[20, 30];
// 方式一:直接获取Span
Span<int> flat = numbers.Flatten();
flat.Fill(42);
// 方式二:使用GridView
var grid = numbers.AsGrid();
grid[5, 10] = 100;
// 手动索引计算
int pos = numbers.ComputeIndex(3, 7);
flat[pos] = 999;
}
性能考量与最佳实践
在使用Span处理多维数组时,需要注意以下几点:
- 多维数组的连续内存布局是使用此技术的前提条件,交错数组不适用此方法
- GridView等包装类型提供了边界检查,比直接使用指针更安全
- 对于绝大多数场景,Span的性能与指针相当
- Span代码的可读性和可维护性显著优于unsafe指针代码
实际应用场景示例
在图像处理中,这种技术特别有用:
public class ImageProcessor
{
public void ApplyFilter(double[,] grayscale)
{
var image = new GridView<double>(grayscale);
int w = image.Width;
int h = image.Height;
// 创建输出图像
double[,] result = new double[h, w];
var output = result.AsGrid();
// 简单的边缘检测(简化版)
for (int y = 1; y < h - 1; y++)
{
for (int x = 1; x < w - 1; x++)
{
double gx = image[y, x+1] - image[y, x-1];
double gy = image[y+1, x] - image[y-1, x];
output[y, x] = Math.Sqrt(gx*gx + gy*gy);
}
}
}
}
版本兼容性说明
MemoryMarshal.GetArrayDataReference和MemoryMarshal.CreateSpan方法需要.NET Core 3.0或更高版本。对于较旧的.NET Framework项目,仍需要使用fixed语句配合指针来实现类似功能。
如果项目需要支持多个.NET版本,可以使用条件编译来处理:
public Span<double> GetArraySpan(double[,] array)
{
#if NETCOREAPP3_0_OR_GREATER
ref double reference = ref MemoryMarshal.GetArrayDataReference(array);
return MemoryMarshal.CreateSpan(ref reference, array.Length);
#else
unsafe
{
fixed (double* ptr = &array[0, 0])
{
return new Span<double>(ptr, array.Length);
}
}
#endif
}
通过合理运用这些技术,我们可以在C#中高效、安全地处理多维数组,获得接近指针操作的性能,同时保持代码的清晰和安全。