【问题标题】:Read SortedList from Hashtable从 Hashtable 中读取 SortedList
【发布时间】:2014-05-24 09:00:34
【问题描述】:

当我在 Hashtable 中有这个结构时,如何从 SortedList 中读取值?

下面是例子

public SortedList sl = new SortedList();
sl[test] = 1;
Hashtable ht= new Hashtable();
ht.Add("root", sl);

我想阅读sl[test]

【问题讨论】:

  • 我可能会建议使用 SortedList 的通用版本:SortedList<TKey, TValue> 而不是使用 Dictionary<TKey, TValue> 的 HashTable(尽管字典不是 HashTable 的 1:1 替换)以避免多余的装箱/拆箱价值观

标签: c# hashtable sortedlist


【解决方案1】:

你只是做相反的事情:

SortedList sortedList = (SortedList)ht["root"];

object value = sortedList[test];

【讨论】:

    【解决方案2】:

    就目前而言,您需要将哈希表的结果转换回SortedList,然后才能对其使用索引器等方法,这需要这种丑陋:

    var result = (ht["root"] as SortedList)[test];
    

    但是,如果您的哈希表的所有元素都是 SortedLists,您可以使用通用容器(例如 Dictionary)来避免强制转换:

    var dic = new Dictionary<string, SortedList> { { "root", sl } };
    result = dic["root"][test];
    

    您还可以考虑将SortedList 替换为其generic counterpart,例如SortedList&lt;string, int&gt;(取决于“测试”的类型),原因相同。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-07-16
      • 2020-02-20
      • 1970-01-01
      • 2016-09-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多