c# - 当 T 不同时,是否可以获取 List<T> 的项目数?

标签 c# generics list

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

提前致谢!

编辑:

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/

相关文章:

c# - 在 C# 中,如何通过 Regex.Replace() 函数获取所有替换的开始/结束索引

c# - Intranet 中的自签名 TLS 证书

java - 以类为键的 TreeMap

java - 如何使用反射和 Guava TypeToken 实例化参数化类的 Class 对象

c# - 根据单词列表搜索短语列表并计算出现次数

c# - 代码量是否会使数据结构变大?

c# - 将 KeyValuePair 列表的内容写入文本文件 - 有一个问题

python - pandas timeseries DF 切片和选择

c# - 如何在 MVC View 中显示对象列表?

python - 如何找到与给定范围元组重叠的元组