c# - C#中填充矩形数组的扩展方法

标签 c# .net arrays

我想为填充多维矩形数组编写扩展方法。我知道如何为具有固定测量次数的阵列执行此操作:

public static void Fill<T>(this T[] source, T value)
{
    for (int i = 0; i < source.Length; i++)
        source[i] = value;
}
public static void Fill<T>(this T[,] source, T value)
{
    for (int i = 0; i < source.GetLength(0); i++)
        for (int j = 0; j < source.GetLength(1); j++)
            source[i, j] = value;
}
public static void Fill<T>(this T[,,] source, T value)
{
    for (int i = 0; i < source.GetLength(0); i++)
        for (int j = 0; j < source.GetLength(1); j++)
            for (int k = 0; k < source.GetLength(2); k++)
                source[i, j, k] = value;
}

我可以为所有多维矩形数组编写一个填充方法吗?

最佳答案

您可以将固定维度参数更改为数组参数,这样您就可以将扩展放在任何数组上。然后我使用递归遍历数组的每个位置。

public static void Fill<T>(this Array source, T value)
{
    Fill(0, source, new long[source.Rank], value);
}

static void Fill<T>(int dimension, Array array, long[] indexes, T value)
{
    var lowerBound = array.GetLowerBound(dimension);
    var upperBound = array.GetUpperBound(dimension);
    for (int i = lowerBound; i <= upperBound; i++)
    {
        indexes[dimension] = i;
        if (dimension < array.Rank - 1)
        {
            Fill(dimension + 1, array, indexes, value);
        }
        else
        {
            array.SetValue(value, indexes);
        }
    }
}

关于c# - C#中填充矩形数组的扩展方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1860333/

相关文章:

c# - 网络摄像头点对点流式传输

c# - WPF 和 WinForms WebBrowser 控件之间存在哪些功能差异?

.net - 为什么.NET框架中没有 "set"接口(interface)?

.net - 如何右键单击打开窗口系统菜单?

arrays - 如何在 Mongodb 的旧版本中获取数组元素的索引?

arrays - 这是 Ruby 中 Array.fill 方法的错误吗?

java - 多态排序转换

c# - 读写装箱双值线程安全且无锁?

c# - .Net 类来控制远程机器上的服务?

.net - 如何在 Excel 中将区域设置应用于十进制格式?