如何在C#中动态更改循环内的变量名?

时间:2013-07-29 14:16:09

标签: c#-4.0

我有循环到listView控件,我想为每个listView内容创建对象,所以我想通过foreach循环逐步改变对象的名称

foreach (var item in listViewStates.Items)
            {
               State s = new State 
               {
                   ID = MaxStateID,
                   Name = listViewStates.Items[0].Text,
                   WorkflowID = MaxWFID,
                   DueDate = Convert.ToInt32(listViewStates.SelectedItems[0].SubItems[1].Text),
                   Priority = Convert.ToInt32(listViewStates.SelectedItems[0].SubItems[2].Text),
                   RoleID = Convert.ToInt32(listViewStates.SelectedItems[0].SubItems[3].Text),
                   Status =Convert.ToInt32(listViewStates.SelectedItems[0].SubItems[4].Text)
               };
               i++;
            }

该变量来自State Class

1 个答案:

答案 0 :(得分:2)

你可能有错误的方法。您需要对状态对象执行的操作是将其添加到集合中,然后从那里开始工作。跟踪这种方式要容易得多。

在循环之后使用本地列表的示例,在函数中:

public void MyFunction()
{
    List<State> states = new List<State>();

    foreach (var item in listViewStates.Items)
    {
        State s = new State
        {
            //Set state properties
        };
        states.Add(s);
    }
    //Use your states here, address with brackets
    //states[0].ID ...
}

具有类级别列表的示例,供以后在函数外部使用:

List<State> _states;

public void MyFunction()
{
    _states = new List<State>();
    foreach (var item in listViewStates.Items)
    {
        State s = new State
        {
            //Set state properties
        };
        _states.Add(s);
    }
    //Now, after calling the function, your states remain
    //You can address them the same way as above, with brackets
    //_states[0].ID ...
}