为每个标签分配一个随机图标 VC++

To assign a random icon to each label VC++

以下是部分代码取自 https://msdn.microsoft.com/en-us/library/dd553230.aspx?cs-save-lang=1&cs-lang=csharp#code-snippet-1


/// Assign each icon from the list of icons to a random square

// The TableLayoutPanel has 16 labels and the icon list has 16 icons,so an icon is pulled at random from the listand added to each label


private void AssignIconsToSquares()
{

    foreach (Control control in tableLayoutPanel1.Controls)
    {
        Label iconLabel = control as Label;
        if (iconLabel != null)
        {
            int randomNumber = random.Next(icons.Count);
            iconLabel.Text = icons[randomNumber];
            // iconLabel.ForeColor = iconLabel.BackColor;
            icons.RemoveAt(randomNumber);
        }
    }
} 

我想在 VC++ 中编写相同的代码。我试过但还没有成功。在VC++中有什么方法可以使用'keyword as'吗?是否可以用 VC++ 语法编写相同的代码。我的代码版本如下,

private: void AssignIconsToSquares()
{
    for each (Label^ label in tableLayoutPanel1)
    {
        if (label != "0")
        {
            Random^ random = gcnew Random();
            int randomNumber = random->Next(0, 17);
            label->Text = icons[randomNumber];
        }
    }
}

我收到很多错误,例如

error C3285: for each statement cannot operate on variables of type 'System::Windows::Forms::TableLayoutPanel ^' left of '->Text' must point to class/struct/union/generic type

如果有人帮我解决这个问题,我将不胜感激。

此致

该错误意味着 Text 成员似乎不属于您正在使用的项目 (label)。

您似乎遗漏了一些端口:

foreach (Control control in tableLayoutPanel1.Controls)
{

我想在您的托管 C++ 示例中它应该是这样的:

private: void AssignIconsToSquares()
{
    for each (Control^ control in tableLayoutPanel1.Controls)
    {
        Label^ thislabel = safe_cast<Label^>(control);
        if (thislabel != NULL)
        {
            Random^ random = gcnew Random();
            int randomNumber = random->Next(0, 17);
            thislabel->Text = icons[randomNumber];
        }
    }
}