c# - 如何在被调用的类中正确初始化二维数组
问题描述
这会引发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
未初始化的运行时错误。我最好的猜测是,我在运行时设置了长度的二维数组没有正确地做某事。
解决方案
在您的构造函数中,您正在执行以下操作:
int[,] EdgeList = new int[(arrayLength * arrayLength), 2];
它创建一个与字段同名的新(本地)变量。相反,您应该这样做:
this.EdgeList = new int[(arrayLength * arrayLength), 2];
您可以省略this
,但它可以防止您再次犯此错误。
此外,您应该将字段声明更改为
public int[,] EdgeList
然后,您可以通过以下方式设置数组中的各个字段:
EdgeList[i,j] = value;
推荐阅读
- openlayers - OpenLayer4.6.5:在本地目录中定义自定义tileImage源
- javascript - Javascript 添加监听器错误:TypeError: trigger.addEventListener is not a function
- postgresql - BIRT - 创建一个临时表
- c - 如何将双精度数据转换为 uint8 数组并再次返回双精度
- iis - rabbitmq con connect 在 iis 上发布后
- android - 滚动recyclerview时RecyclerView项目不调整它的高度
- python - 使用 Pandas 在列中循环字典
- r - countrycode 包没有将 cown 转换为 iso3c
- javascript - 如何阻止用户从我的页面复制纯文本以及下载我帖子中的任何图像,他也不能右键单击页面?
- javascript - 使用 ?:(javascript 中的条件运算符)的函数解释