当前位置:首页 > 技术 > 正文内容

C#中使用Span操作多维数组的完全指南

访客 技术 2026年7月4日 2

多维数组与Span的技术深度解析

在C#编程中,处理多维数组是一项常见需求。当我们需要高性能地访问这些数组时,Span提供了一个安全且高效的替代方案。本文将深入探讨如何在不同.NET版本中实现这一目标。

理解多维数组的内存布局

与交错数组(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#中高效、安全地处理多维数组,获得接近指针操作的性能,同时保持代码的清晰和安全。

相关文章

Linux crontab 详解

1) crontab 是什么cron 是 Linux 的定时任务守护进程;crontab 是用来编辑/查看“按时间周期执行命令”的表(cron table)。常见两类:用户 crontab:每个用户一份(crontab -e 编辑)系统级 crontab / cron.d:可指定执行用户(/etc/crontab、/etc/cron.d/*)2) crontab 时间...

富文本里可以允许的 HTML 属性

一、所有标签默认允许的安全属性(极少)class        (可选)id           (通常建议禁用)title️ 注意:id 容易被滥用做锚点注入,很多系统直接禁用class 允许的话最好只允许固定前缀(如 editor-*)二、a 标签允许属性<a href="" t...

Mac 安装 Node.js 指南

方法一:通过官网安装包(最简单,适合初学者)如果你只是想快速安装并开始使用,这是最直接的方法。访问 Node.js 官网。页面会显示两个版本:LTS (Recommended For Most Users):长期支持版,最稳定。建议选这个。Current:最新特性版,包含最新功能但可能不够稳定。下载 .pkg 安装包并运行。按照安装向导点击“下一步”即可完成。方法二:使用 Homebrew 安装(...

Dom\HTML_NO_DEFAULT_NS 的副作用:自动加闭合标签

在使用Dom\HTMLDocument时,Dom\HTML_NO_DEFAULT_NS 将禁止在解析过程中设置元素的命名空间, 此设置是为了与DOMDocument向后兼容而存在的。当使用它时,已知的一个副作用就是:自动加闭合标签例如 </img> 为什么会这样?当你使用:Dom\HTML_NO_DEFAULT_NS文档会变成 无命名空间模式,此时内部更接近 XML...

Laravel 事件和监听器创建

在 Laravel 中,使用 Artisan 命令创建 Events(事件) 和 Listeners(监听器) 是非常高效的。你可以通过以下几种方式来实现:1. 手动创建单个 Event如果你只想创建一个事件类,可以使用 make:event 命令:Bashphp artisan make:event UserRegistered执行后,文件将生成在 app/Even...

自定义域名解析神器 dnsmasq

什么是 dnsmasq?dnsmasq 是一个轻量级、功能强大的网络服务工具,专为小型和中等规模网络设计。它是一个综合的网络基础设施解决方案[1]。dnsmasq 能做什么?功能说明应用场景DNS 转发与缓存将 DNS 查询转发到上游服务器(ISP、Google DNS 等),并在本地缓存结果加快 DNS 查询速度,减少外部 DNS 流量本地 DNS解析本地网络设备的主机名,无需编辑&n...

发表评论

访客

◎欢迎参与讨论,请在这里发表您的看法和观点。