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

时间:2016-05-18 13:59:34

标签: c# visual-c++ c++-cli

以下是代码的一部分 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 ++?是否可以在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];
        }
    }
}

我收到很多错误,比如

  

错误C3285:对于每个语句都不能对类型为' System :: Windows :: Forms :: TableLayoutPanel ^'的变量进行操作。左边的' - >文字'必须指向class / struct / union / generic类型

如果有人帮我解决这个问题,那么会有效吗。

此致

1 个答案:

答案 0 :(得分:-1)

错误表示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];
        }
    }
}