c# - 可以使用数组访问 C# 多维数组索引器吗?

标签 c# multidimensional-array indexing

我试图弄清楚是否可以将对象作为多维数组的索引值传递。

var nums = new int[3,3];
// of course you can index by literal integers
nums[0, 2] = 99;
// but can you index by an array?  This does not work
var index = new [] {0, 2};
nums[index] = 100;

// I can use GetValue with the int array, but this returns an object not an int
nums.GetValue(new [] {0, 2});

那么有谁知道我应该将什么类型传递给多维数组索引器以满足编译器的要求?

最佳答案

简短的回答是否定的,您本身无法执行此操作。

稍微长一点的答案是肯定的,您可以使用扩展方法来实现此类行为。您可以添加一个适用于所有数组的扩展方法,如下所示:

public static class ArrayExtender
{
    public static T GetValue<T>(this T[,] array, params int[] indices)
    {
        return (T)array.GetValue(indices);
    }

    public static void SetValue<T>(this T[,] array, T value, params int[] indices)
    {
        array.SetValue(value, indices);
    }

    public static T ExchangeValue<T>(this T[,] array, T value, params int[] indices)
    {
        var previousValue = GetValue(array, indices);
        array.SetValue(value, indices);

        return previousValue;
    }
}

这样你就可以使用:

        var matrix = new int[3, 3];
        matrix[0, 2] = 99;

        var oldValue = matrix.GetValue(0, 2);
        matrix.SetValue(100, 0, 2);
        var newValue = matrix.GetValue(0, 2);

        Console.WriteLine("Old Value = {0}", oldValue);
        Console.WriteLine("New Value = {0}", newValue);

输出:

Old Value = 99
New Value = 100

在大多数情况下,对于为什么需要此功能有一个面向对象的答案,并且可以创建适当的自定义类来促进这一点。例如,我可能有一个棋盘,我使用辅助方法创建了多个类:

class GameBoard
{
  public GamePiece GetPieceAtLocation(Point location) { ... }
}

关于c# - 可以使用数组访问 C# 多维数组索引器吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21318792/

相关文章:

python - 选择 Pandas 中特定行上方和下方的 N 行

c# - 动态嵌套循环

c# - 使用 C# 控制台应用程序为 IIS 应用程序池设置文件夹权限

c# - 我可以在 C# winforms 中使用 foreach 循环评估两组项目吗?

javascript - 在 JavaScript 中对多维数组使用过滤方法

arrays - 为什么Powershell会合并数组数组?

c - 如何在c中将字符数组转换为二进制,反之亦然

postgresql - postgres中大型数据库的索引

c# - 选择正确的事件处理程序

python - 列表索引超出范围(使用 while 循环)