[英]How to correctly initialize a 2D array in a called class
This is throwing an error that EdgeList
is not initialized. 这引发了EdgeList
未初始化的错误。 Here is the class (the pertinent part is way at the bottom): 这是类(相关的部分在底部):
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];
}
}
And this is how I'm calling and initializing it (snippet): 这就是我调用和初始化它的方式(摘要):
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 */
// ...
}
}
I'm getting a runtime error that EdgeList
is not initialized. 我收到一个未初始化EdgeList
的运行时错误。 My best guess is that I'm not doing something correctly with a 2D array with the length set at runtime. 我最好的猜测是,我没有使用在运行时设置长度的2D数组正确地执行操作。
I'm sure it's something stupid. 我敢肯定这很愚蠢。 Help would be greatly appreciated. 帮助将不胜感激。 Thanks! 谢谢!
In your constructor, you are doing: 在构造函数中,您正在执行:
int[,] EdgeList = new int[(arrayLength * arrayLength), 2];
which creates a new (local) variable with the same name as the field. 这会创建一个与字段名称相同的新(本地)变量。 Instead you should do: 相反,您应该这样做:
this.EdgeList = new int[(arrayLength * arrayLength), 2];
You could omit the this
, but it can prevent you from making this mistake again. 您可以省略this
,但是可以防止您再次犯此错误。
Further, you should change the field declaration to 此外,您应该将字段声明更改为
public int[,] EdgeList
Then you can set individual fields in the array via: 然后,您可以通过以下方式在数组中设置各个字段:
EdgeList[i,j] = value;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.