You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C#中如何获取object类型列表的Count值

嘿,这个场景我太熟了!你把泛型列表存在object类型变量里,直接访问Count肯定行不通——因为object本身压根没这个属性。这里给你几种靠谱的解决办法,按需选就行:

1. 显式类型转换(确定类型时用)

如果百分百确定test就是List<string>,直接强制转换后访问Count就行:

object test = new List<string>() { "test1", "test2" };
int count = ((List<string>)test).Count; // 结果是2

注意:如果test实际不是List<string>,这行代码会抛出InvalidCastException,所以只适合类型明确的场景。

2. 用as关键字安全转换(不确定类型时用)

要是不确定test的具体类型,用as转换更稳妥——转换失败会返回null,不会直接报错,再搭配空合并运算符处理空值:

object test = new List<string>() { "test1", "test2" };
var stringList = test as List<string>;
int count = stringList?.Count ?? 0; // 转换失败时返回0

3. 借助ICollection接口(通用集合场景)

因为所有List类都实现了System.Collections.ICollection接口,而这个接口刚好有Count属性。这种方法不用绑定具体泛型类型,适配更多集合:

object test = new List<string>() { "test1", "test2" };
var collection = test as System.Collections.ICollection;
int count = collection?.Count ?? 0;

哪怕test是List<int>或者HashSet<string>,这种方式也能正常获取元素数量。

4. 动态类型dynamic(快速测试场景)

把变量转成dynamic,让运行时自动解析Count属性,写法最简洁,但要承担运行时风险:

object test = new List<string>() { "test1", "test2" };
dynamic dynamicList = test;
int count = dynamicList.Count;

⚠️ 注意:如果test实际没有Count属性,运行时会抛出RuntimeBinderException,所以只适合你明确知道对象有这个属性的情况。

内容的提问来源于stack exchange,提问作者Tobias Møller

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 03:44:12