Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在C#中声明枚举的二维数组?_C#_Arrays_Enums - Fatal编程技术网

如何在C#中声明枚举的二维数组?

如何在C#中声明枚举的二维数组?,c#,arrays,enums,C#,Arrays,Enums,我正在从Java转换到C#,我想知道这是否可能?我想做的是创建一个二维数组,类型为Enum{north,south,east,west}。这样我就可以调用map[1,2].north来确定地图上的单元格是否有北墙 对不起,代码太粗糙了,我现在无法访问我的计算机,所以我有点抽象 试试看: private EnumName[,] arrayName; 对于枚举: enum Dirs { North, South, East, West } 只需将数组声明为: Dirs[,] dirs = ne

我正在从Java转换到C#,我想知道这是否可能?我想做的是创建一个二维数组,类型为
Enum{north,south,east,west}
。这样我就可以调用
map[1,2].north
来确定地图上的单元格是否有北墙

对不起,代码太粗糙了,我现在无法访问我的计算机,所以我有点抽象

试试看:

private EnumName[,] arrayName; 
对于枚举:

enum Dirs { North, South, East, West }
只需将数组声明为:

Dirs[,] dirs = new Dirs[10, 10];
如果需要每个单元格都有几面墙,请使用
[Flags]
属性标记枚举,并将值设为2的幂:

[Flags]
enum Dirs { North = 1 << 0, South = 1 << 1, East = 1 << 2, West = 1 << 3 }
正如@在他的评论中提到的,要检查方向,您可以:

bool hasNorthWall = dirs[1, 2].HasFlag(Dirs.North);

这就是如何使用
枚举声明和测试墙

namespace ConsoleApplication1
{
    [Flags]
    enum Wall
    {
        North = 1,
        South = 2,
        East  = 4,
        West  = 8
    }
    static class Program
    {
        static void Main(string[] args)
        {
            int grid = 10;
            var map=new Wall[grid, grid];
            // fill in values here ...
            if(map[1, 2].HasFlag(Wall.North))
            {
                // cell (2, 3) has a wall in the north direction
            }
        }
    }
}

一个单元格可以有多个墙吗?因为您来自Java,您可能想知道C#中的
enum
是。
Flags
属性不会更改enum成员的值。如果使用它,则需要显式地将值设置为2的幂,否则最终会出现一些不希望出现的行为@ScottChamberlain补充了答案,谢谢。另一个有用的提示。当您需要将标志的幂为2时,只需使用左移位运算符
[flags]enum Dirs{North=1@ScottChamberlain嗯,我同意,这对那些至少不记得2到16位的所有幂的人来说是很有意义的。:p
namespace ConsoleApplication1
{
    [Flags]
    enum Wall
    {
        North = 1,
        South = 2,
        East  = 4,
        West  = 8
    }
    static class Program
    {
        static void Main(string[] args)
        {
            int grid = 10;
            var map=new Wall[grid, grid];
            // fill in values here ...
            if(map[1, 2].HasFlag(Wall.North))
            {
                // cell (2, 3) has a wall in the north direction
            }
        }
    }
}