簡體   English   中英

將值添加到for循環內的PointF數組時,出現“預期為常數”錯誤

[英]“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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM