0

我已经声明了以下结构:

struct StartPositions
{
    public Vector2 pacman;
    public Vector2[] ghosts;

    // Constructor accepts a Vector2, and an array of Vector2's.
    public StartPositions(Vector2 pacmanPosIn, Vector2[] ghostsPosIn)
    {
        pacman = pacmanPosIn;
        for(int a=0;a<ghostsPosIn.Length;a++)
        {
            ghosts[a] = ghostsPosIn[a];
        }
    }
}

但是,我收到一个编译器错误,提示必须完全分配 ghosts 字段。我想要做的是在创建 StartPositions 对象时传入一个 Vector2 和一个 Vector2 数组 - 制作该数组的副本。

我怎样才能正确地做到这一点?

4

4 回答 4

2

您没有初始化ghosts数组。您需要添加对 的调用new

public StartPositions(Vector2 pacmanPosIn, Vector2[] ghostsPosIn)
{
    pacman = pacmanPosIn;
    ghosts = new Vector2[ghostsPosIn.Length];
    ....
}

您可以通过将for循环替换为对Array.Copy().

Array.Copy(ghostsPosIn, ghosts, ghosts.Length);
于 2013-04-14T15:45:34.030 回答
1

你必须先初始化你的ghosts数组:

struct StartPositions
{
    public Vector2 pacman;
    public Vector2[] ghosts;

    // Constructor accepts a Vector2, and an array of Vector2's.
    public StartPositions(Vector2 pacmanPosIn, Vector2[] ghostsPosIn)
    {
        pacman = pacmanPosIn;
        ghosts = new Vector2[ghostsPosIn.Length];
        for(int a=0;a<ghostsPosIn.Length;a++)
        {
            ghosts[a] = ghostsPosIn[a];
        }
    }
}
于 2013-04-14T15:44:58.733 回答
0

你没有初始化ghosts数组。

public StartPositions(Vector2 pacmanPosIn, Vector2[] ghostsPosIn)
{
    ...
    ghosts = new Vector2[ghostsPosIn.Length];
    ...
}

来自C# 语言规范

实际的数组实例是在运行时使用 new运算符动态创建的。新操作指定新数组实例的长度, 然后在实例的生命周期内固定。

于 2013-04-14T15:46:21.703 回答
0

One annoying quirk in .net is that unless one is using "unsafe" code the concept of a value-type array does not exist. The struct as shown contains a position for the "pacman" and a reference to a mutable array that holds the positions of the ghosts. This is an evil combination, since the struct may appear to encapsulate the positions of the ghosts, but it does not. Thus, if one were to say:

StartPositions p1 = whatever();
... do some stuff
StartPositions p2 = p1;
p2.pacman.X += 3;
p2.ghosts[0].X += 3;

the code would add three to p2.pacman and p2.ghosts[0]; it would not affect p1.pacman.X but would add three to p1.ghosts[0]. Such behavior would likely cause confusion.

If your intention is that StartPositions will be read-only, it should probably never expose the ghosts array directly; instead, ghosts should be a property of type IList<Vector2>, and your constructor should set it to something like a new ReadOnlyList<Vector2> initialized with a copy of the passed-in positions. If it does that, then ghosts can simply be a read-only property that returns such positions.

于 2013-04-15T16:39:43.563 回答