开发者

Is this array initialization incorrect?

开发者 https://www.devze.com 2023-03-02 16:19 出处:网络
public byte[][,] Shapes = { { {1,1}, {1,1} }, { {1}, {1}, {1}, {1} }, { {0,0,1}, {1,1,1} } }; I get this error: \"Array initializers can only be used in a variable or field initializer. Tr开发
public byte[][,] Shapes = 
    {
        {
            {1,1}, 
            {1,1}
        }, 
        {
            {1}, 
            {1}, 
            {1}, 
            {1}
        },
        {
            {0,0,1},
            {1,1,1}
        }
    };

I get this error: "Array initializers can only be used in a variable or field initializer. Tr开发者_开发知识库y using a new expression instead."

I could do this...

public class Shape
{
    public byte[][,] Shapes;

    public Shape()
    {
        Shapes = new byte[3][,];

        Shapes[0] = new byte[2, 2];
        Shapes[0][0, 0] = 1;
        Shapes[0][0, 1] = 1;
        Shapes[0][1, 0] = 1;
        Shapes[0][1, 1] = 1;

        Shapes[1] = new byte[1, 4];
        Shapes[1][0, 0] = 1;
        Shapes[1][0, 1] = 1;
        Shapes[1][0, 2] = 1;
        Shapes[1][0, 3] = 1;
    }
}

But that makes it very hard to add more shapes to my program.

Is my initializer wrong? And if I'm not allowed to do it this way, what's the easiest way to set it out?


This works for me:

  public byte[][,] Shapes = new byte[3][,]
    {
        new byte[,] { {1,1}, {1,1} },
        new byte[,] { {1}, {2}, {3}, {4} },
        new byte[,] { {0,0,1}, {1,1,1} }
    };


Array initializer syntax ({ ... }) can only be used to initialize a field or variable.
To make arrays inside the outer array, you need to use normal array creation syntax.

Add new [] before the inner { ... } to create an implicitly-typed array.

Since you're dealing with bytes and multi-dimensional arrays, you may need to explicitly specify some of the types, by writing new byte[,] { ... }.

0

精彩评论

暂无评论...
验证码 换一张
取 消