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

如何从Hashtable中获取字符串列表?解决对象类型无法索引问题

解决Hashtable获取列表值时的索引报错问题

问题原因

Hashtable是非泛型集合,它存储的所有元素都会被装箱为object类型。当你通过hshTable["1"]取值时,返回的是object,而object类型不支持索引器操作,所以会报错Cannot apply indexing with [] to an expression of type 'object'。

解决办法

1. 显式强制类型转换

把Hashtable中取出的object转换为List<string>后再使用索引:

// 分步转换,可读性更好
List<string> targetList = (List<string>)hshTable["1"];
string temp = targetList[0];

// 或者合并为一行
string temp = ((List<string>)hshTable["1"])[0];

注意:如果键不存在或者对应值不是List<string>,强制转换会抛出InvalidCastException或NullReferenceException。

2. 使用as运算符安全转换

如果不确定键是否存在或值的类型是否匹配,用as转换更安全,转换失败会返回null,避免抛出异常:

List<string> targetList = hshTable["1"] as List<string>;
if (targetList != null)
{
    string temp = targetList[0];
    // 执行后续逻辑
}
else
{
    // 处理键不存在或类型不匹配的情况
}

3. 改用泛型集合Dictionary<TKey, TValue>(推荐)

Hashtable是.NET早期的非泛型集合,现在更推荐使用泛型的Dictionary,它支持指定键值对的类型,无需装箱拆箱,类型安全性更高,代码更简洁:

// 定义泛型字典,指定键为string,值为List<string>
Dictionary<string, List<string>> dict = new Dictionary<string, List<string>>();
List<string> l = new List<string>();
l.Add("string1");
l.Add("string2");
dict.Add("1", l);

// 直接通过索引访问,无需类型转换
string temp = dict["1"][0];

内容的提问来源于stack exchange,提问作者IDONKNOW3333333333

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 19:20:15