[英]“A constant value is expected” error when adding values to PointF array inside for loop
我是C#编程的新手。 我的项目遇到困难。 这是东西。 -我有一个MCvBox2dD名称lstRectangles的列表-我想获取每个框的中心并将其全部放置在名为center的PointF数组上。
这是我的代码:
List<MCvBox2D> lstRectangles; // stores data of detected boxes
...
int size = lstRectangles.Count(); //total boxes detected
PointF[] center = null; //array of PointF where I want to transfer the center of each detected boxes
for (int j = 0; j < lstRectangles.Count(); j++)
{
center = new PointF[j] // here is the error, "A constant value is expected"
{
new PointF(lstRectangles[j].center.X , lstRectangles[j].center.Y)
};
}
在这种情况下,您既要指定数组的确切大小,又要指定组成数组的元素集。 C#必须选择这些值之一作为数组的大小。 在这种情况下, j
不是常数,因此无法验证这两个数字是否匹配,并且发出错误。
要解决此问题,只需删除size参数,然后让C#根据您使用的元素数推断大小
center = new PointF[]
{
new PointF(lstRectangles[j].center.X , lstRectangles[j].center.Y)
};
尽管基于上下文,但您实际上要执行的工作是在j
的数组中分配一个新的PointF
。 如果是这样,请执行以下操作
center[j] = new PointF(lstRectangles[j].center.X , lstRectangles[j].center.Y);
首先,您需要声明PointF数组的大小(等于lstRectangle元素)
然后,将正确的语法添加到数组中的新语法如下:
int size = lstRectangles.Count();
PointF[] center = new PointF[size];
for (int j = 0; j < lstRectangles.Count(); j++)
{
center[j] = new PointF(lstRectangles[j].center.X , lstRectangles[j].center.Y)
}
但是,我建议不要使用数组,而建议使用List<PointF>
List<PointF> center = new List<PointF>();
foreach(MCvBox2D box in lstRectangles)
{
center.Add(new PointF(box.center.X , box.center.Y));
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.