2010-07-29 21 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

相關問題