使用点从多维数组中获取值

时间:2014-06-22 10:56:52

标签: c# arrays multidimensional-array

我有一个像这样的多维数组:

int[,] map = new int[4,4];

我在代码中使用了很多Point,所以当我需要数组的值时:

void Something(Point start){
    int val = map[start.X, start.Y];
    // the rest of the code
}

无论如何,我可以直接使用Point从我的数组中获取所需的值:

int val = map[start];

1 个答案:

答案 0 :(得分:3)

如果这是您正在使用的.NET 3.5+,您可以创建一个扩展方法来获取数据:

public static class ExtensioMethods
{
    public static int Get(this int[,] array, Point p)
    {
        return array[p.X, p.Y];
    }
}

并在你的代码中使用它:

int val = map.Get(start);