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

本文关键字:数组 获取 | 更新日期: 2023-09-27 18:09:39

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

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

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

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

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

int val = map[start];

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

如果你使用的是。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);
相关文章: