简体   繁体   English

将值添加到for循环内的PointF数组时,出现“预期为常数”错误

[英]“A constant value is expected” error when adding values to PointF array inside for loop

im a newbie in C# programming. 我是C#编程的新手。 I having difficulties with my project. 我的项目遇到困难。 Here is the thing. 这是东西。 - I have a list of MCvBox2dD name lstRectangles - I want to get the center of each box and place it all on PointF array named center. -我有一个MCvBox2dD名称lstRectangles的列表-我想获取每个框的中心并将其全部放置在名为center的PointF数组上。

here is my code: 这是我的代码:

        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)
            };

        }

In this case you've both specified an exact size of the array and the set of elements that make up the array. 在这种情况下,您既要指定数组的确切大小,又要指定组成数组的元素集。 C# has to pick one of these values to use as the size of the array. C#必须选择这些值之一作为数组的大小。 In this case j is not a constant hence it can't validate that these two numbers match up and it's issuing an error. 在这种情况下, j不是常数,因此无法验证这两个数字是否匹配,并且发出错误。

To fix this just remove the size argument and let C# infer the size based on the number of elements you use 要解决此问题,只需删除size参数,然后让C#根据您使用的元素数推断大小

center = new PointF[]
{
  new PointF(lstRectangles[j].center.X , lstRectangles[j].center.Y)
};

Based on the context though it looks like what you're really trying to do is assign a new PointF into the array at j . 尽管基于上下文,但您实际上要执行的工作是在j的数组中分配一个新的PointF If so then do the following 如果是这样,请执行以下操作

center[j] = new PointF(lstRectangles[j].center.X , lstRectangles[j].center.Y);

First you need to declare the size for your array of PointF (equals to the lstRectangle elements) 首先,您需要声明PointF数组的大小(等于lstRectangle元素)
Then the correct syntax to add a new PointF to the array is the following 然后,将正确的语法添加到数组中的新语法如下:

    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)
    }

However, instead of using an array, I suggest to use a List<PointF> 但是,我建议不要使用数组,而建议使用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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM