首页 > 解决方案 > 如何在被调用的类中正确初始化二维数组

问题描述

这会引发EdgeList未初始化的错误。这是课程(相关部分在底部):

public class TacLineStruct
{
    // The number of unit groups in the Army
    public int NumGroups
    {
        get
        {
            return _NumGroups;
        }
        set
        {
            _NumGroups = value;
        }
    }
    private int _NumGroups;

    // The number of edges, 
    public int NumEdges
    {
        get
        {
            return _NumEdges;
        }
        set
        {
            _NumEdges = value;
        }
    }
    private int _NumEdges;

    // The number of units below the threshold 
    public int NumBelowThreshold
    {
        get
        {
            return _NumBelowThreshold;
        }
        set
        {
            _NumBelowThreshold = value;
        }
    }
    private int _NumBelowThreshold;

    // The specific Group that a unit belongs to
    public int[] GroupID
    {
        get;
        set;
    }

    // The list of all the edges
    public int[][] EdgeList
    {
        get;
        set;
    }

    // The list of all the edge weights
    public float[] EdgeWeight
    {
        get;
        set;
    }

    // The geographical center of each group
    public Point[] GroupCenter
    {
        get;
        set;
    }

    public TacLineStruct(int arrayLength)
    {
        GroupID = new int[arrayLength];
        int[,] EdgeList = new int[(arrayLength * arrayLength),2];
        EdgeWeight = new float[arrayLength * arrayLength];
        GroupCenter = new Point[arrayLength];
    }
}

这就是我调用和初始化它的方式(片段):

TacLineStruct TLS = new TacLineStruct(Army.Count);

for (int i = 0; i <= Army.Count; i++)
{
    for (int j = i + 1; j <= Army.Count; j++)
    {
        TLS.EdgeList[NumEdges][0] = i;     /* first vertex of edge */
        TLS.EdgeList[NumEdges][1] = j;     /* second vertex of edge */
        
        // ...
    }
}

我收到EdgeList未初始化的运行时错误。我最好的猜测是,我在运行时设置了长度的二维数组没有正确地做某事。

标签: c#classmultidimensional-arrayinitialization

解决方案


在您的构造函数中,您正在执行以下操作:

int[,] EdgeList = new int[(arrayLength * arrayLength), 2];

它创建一个与字段同名的新(本地)变量。相反,您应该这样做:

this.EdgeList = new int[(arrayLength * arrayLength), 2];

您可以省略this,但它可以防止您再次犯此错误。

此外,您应该将字段声明更改为

public int[,] EdgeList

然后,您可以通过以下方式设置数组中的各个字段:

 EdgeList[i,j] = value; 

推荐阅读