2010-07-29 29 views
2

我有一个子程序,稍微改变其操作以包括一个列表或其他,然后执行相同的操作。由于它只计算列表中的项目数量,所以我认为无论列表类型如何,都可能有一种简单的方法来获取项目计数。当T不同时,是否有可能获得列表<T>的项目数?

在此先感谢!

编辑:

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); 
    } 
+3

为什么要“计数”列表中的项目数而不是访问Count属性? – 2010-07-29 22:30:19

+0

我相信这是列表的模糊性,我会添加一些代码来更好地展示我在做什么。 – Anders 2010-07-29 22:31:57

回答

8

您可以随时使用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以更好地传达类型信息,并完全避免所有此类废话。

+0

完美,这正是我所需要的。谢谢! – Anders 2010-07-29 22:37:36

+0

也采取了更好的选择。再次感谢你。 – Anders 2010-07-29 22:40:06

1
ICollection temp; 
     if (includeAllCheck.Checked) 
     { 

      temp = currentMessages;    
     } 
     else 
     { 
      temp = currentLeads; 

     } 
if (SelectedLead == (temp.Count - 1)) 
       SelectedLead = 0; 
      else 
       SelectedLead += 1; 
+0

这是我询问的正确解决方案。在你做之前,LBushkin就把它拿走了。然而,感谢您的输入! – Anders 2010-07-29 22:44:16

相关问题