代码之家  ›  专栏  ›  技术社区  ›  Anders

当t不同时,是否可以获取列表的项目计数?

  •  2
  • Anders  · 技术社区  · 14 年前

    我有一个子例程,它稍微改变它的操作,以包含一个列表或另一个列表,然后执行相同的操作。因为它只是计算列表中的项目数,所以我认为无论列表类型如何,都可能有一种简单的方法来获取项目数。

    事先谢谢!

    编辑:

    private List<Message> currentMessages;
    private List<Lead> currentLeads; 
    ...
    private void nextLeadBtn_Click(object sender, EventArgs e)
        {
            object temp;
            if (includeAllCheck.Checked)
            {
    
                temp = currentMessages;
                if (SelectedLead == (currentMessages.Count - 1))
                    SelectedLead = 0;
                else
                    SelectedLead += 1;
            }
            else
            {
                temp = currentLeads;
                if (SelectedLead == (currentLeads.Count - 1))
                    SelectedLead = 0;
                else
                    SelectedLead += 1;  
            }
            // This is what I want to replace the above with
            //if (SelectedLead == ((List)temp).Count - 1) //obviously this does not work
            //    SelectedLead = 0;
            //else
            //    SelectedLead += 1;
    
    
    
    
            LoadPreviews(includeAllCheck.Checked);
        }
    
    2 回复  |  直到 14 年前
        1
  •  8
  •   LBushkin    14 年前

    你可以一直使用 ICollection.Count 如果你不想处理仿制药的话。 List<T> 器具 ICollection ,所以您可以随时访问它。

    编辑:现在您已经发布了代码,您只需更改行:

    if (SelectedLead == ((List)temp).Count - 1)  // won't compile, of course
    

    if (SelectedLead == ((ICollection)temp).Count - 1)  // happy as a clam
    

    事实上, 更好的选择 将要更改的声明 object temp ICollection temp 为了更好地传递类型信息,并避免所有这些铸造废话。

        2
  •  1
  •   Coding Flow    14 年前
    ICollection temp;
            if (includeAllCheck.Checked)
            {
    
                temp = currentMessages;            
            }
            else
            {
                temp = currentLeads;
    
            }
    if (SelectedLead == (temp.Count - 1))
                    SelectedLead = 0;
                else
                    SelectedLead += 1;