0

我有 foreach 循环到 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++;
            }

变量是来自状态类的 s

4

1 回答 1

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 ...
}
于 2013-07-29T14:19:08.567 回答