我有一个子程序,它稍微改变它的操作,包括一个列表或另一个列表然后执行相同的操作。由于它只是计算列表中的项目数,我认为无论列表类型如何,都可能有一种简单的方法来获取项目。
提前致谢!
修改
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);
}
答案 0 :(得分: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
以更好地传达类型信息,并完全避免所有这些无意义的废话
答案 1 :(得分:1)
ICollection temp;
if (includeAllCheck.Checked)
{
temp = currentMessages;
}
else
{
temp = currentLeads;
}
if (SelectedLead == (temp.Count - 1))
SelectedLead = 0;
else
SelectedLead += 1;