【问题标题】:foreach items in hashtableforeach 哈希表中的项目
【发布时间】:2015-05-12 11:43:28
【问题描述】:

我需要使用Hastable(不是List 而不是Dictionary),而且我有很多带键的变量。我在类中添加键和变量,并在我的程序中使用它。但我不知道如何解析Hashtable。我试过这个:

        Hashtable toboofer = null;

        string path = @"my.bin";

        FileStream fin = File.OpenRead(path);

        try
        {
            BinaryFormatter bf = new BinaryFormatter();

            toboofer = (Hashtable)bf.Deserialize(fin);

            for (int i = 0; i <= toboofer.Count; i++ )
                //foreach (KeyValuePair<string, string> kvp in toboofer)
                {
                    myclass cl = new myclass();
                    cl.Fio = toboofer[i].ToString();
                    cl.About = toboofer[i].ToString();
                }
        }

但我有一个错误。当我尝试string item 或循环for 时,我也遇到了错误。

【问题讨论】:

  • 你得到什么错误?
  • 你真的应该考虑使用强类型 Dictionary&lt;TKey, TValue&gt; 而不是 Hashtable
  • 那么,为什么Dictionary&lt;,&gt;List&lt;&gt; 解决方案不可接受?可能有一种方法可以回避有助于此解析部分的要求。
  • 字典和列表不会从二进制文件中分离出来。可能是我错了

标签: c# hashtable


【解决方案1】:

Hashtable 具有 DictionaryEntry 作为集合元素

foreach (DictionaryEntry entry in toboofer)
{
    // do something
}

从哈希表中列出myclass

var listOfMyClass = toboofer.Cast<DictionaryEntry>().
                             Select(e => new myclass() 
               { Fio = e.Key.ToString(), About = e.Value.ToString() });

【讨论】:

    【解决方案2】:

    在 DictionaryEntry 中尝试使用这个哈希表,其中 KeyValuePair 由通用字典 .Net 2(及更高版本)使用

    另外请注意,Hashtable 没有它的通用版本,并且 hastable 中的每个元素都由 DictionaryEntry 表示

    foreach (DictionaryEntry entry in hashtable)
        {
            Console.WriteLine("{0}, {1}", entry.Key, entry.Value);
        }
    

    【讨论】:

      猜你喜欢
      • 2023-04-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-25
      • 2021-04-06
      • 2013-07-27
      • 2020-09-02
      • 2012-05-12
      相关资源
      最近更新 更多