我有一个子例程,它稍微改变了它的操作以包含一个列表或另一个然后执行相同的操作。由于它只是计算列表中的项目数,我认为无论列表类型如何,都可能有一种简单的方法来获取项目数。
提前致谢!
编辑:
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);
}
最佳答案
您可以随时使用 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
更好地传达类型信息,并完全避免所有这些乱码。
关于c# - 当 T 不同时,是否可以获取 List<T> 的项目数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3367470/