Foreach问题

时间:2011-02-02 14:24:25

标签: c# foreach

我正在尝试使用foreach语句。我希望能够做到这样的事情:

foreach (int item in itemcount)
  {
     label{0}.Text = item.ToString()
  }

其中{0}是项目中的数字。

这可能吗?

8 个答案:

答案 0 :(得分:5)

您可以这样做:

foreach (int item in itemcount)
{
    Controls[string.Format("label{0}", item.Id)].Text = item.ToString();
}

此外,如果需要访问标签类的属性,则需要将左表达式转换为Label类。

答案 1 :(得分:1)

如果您的课程是ASP.NET页面,那么您应该可以使用FindControl找到它:

foreach (int item in itemcount)
{
    string name = string.Format("label{0}", item);
    Label label = FindControl(name) as Label;
    if (label != null)
    {
        label.Text = name;
    }
}

答案 2 :(得分:0)

如果您尝试以编程方式访问变量名称,则需要使用Reflection。

答案 3 :(得分:0)

在我的头顶,答案是否定的。由于您无法访问foreach循环正在使用的迭代器。

而是做这样的事情

IList<Label> labels = new ArrayList<Label>();
for(int i = 0;i<labels.count;i++)
{
    labels[i].text = i.toString();
}

答案 4 :(得分:0)

“label”是一个数组吗?然后你应该这样做:

label[item] = item.ToString();

如果label不是数组,可能你应该使用数组而不是像label0,label1那样使用变量名......这比使用反射要容易得多。

答案 5 :(得分:0)

foreach (int item in itemcount)
  {
     label[label.IndexOf(item)].Text = item.ToString()
  }

如果我需要假设“label”是一个标签列表(List / IList),你有一个用[]访问的索引器,并且列表有一个IndexOf方法接受整个列表中给定的现有对象返回“项目”的索引 - 在列表中 - ,您可以在MSDN中查看:

答案 6 :(得分:0)

只是为了抛出答案,取决于itemcount类型,你可以写:

Array.ForEach(itemcount, item => label[Convert.ToInt32(item)].Text = item.ToString());

如果itemcountobject[]

itemcount.ForEach(item => label[Convert.ToInt32(item)].Text = item.ToString());

如果itemcountList<object>

答案 7 :(得分:0)

虽然前面发布的那些示例的代码严格意义上回答了这个问题,但是沿着这条路走下去似乎真的很糟糕。

根据您的需求以及您正在使用的框架,您最好使用其他技术。控件数组是一种选择;如果你正在使用WPF,那么使用一个可以将其元素可视化为标签的列表可以非常优雅地实现这一点(你应该免费获得它,但如果不是,那么更改控件的ItemTemplate是很简单的 - 抱歉,我不知道我手头有任何例子。)