【问题标题】:How to write a Hashtable into the file?如何将哈希表写入文件?
【发布时间】:2015-08-29 07:51:37
【问题描述】:

如何在不知道的情况下将哈希表写入文件 里面是什么?!

Hashtable DTVector = new Hashtable();

只需将其存储到文件中,然后读取并再次创建哈希表。

【问题讨论】:

  • 看这里的讨论:stackoverflow.com/questions/10615896/…作者提出了一个解决方案。我无法评价它的质量
  • 你知道里面会有哪些类型吗?我不是指确切的实例,只是它可能的类型(您拥有的类,框架类...)
  • @Gusman 类似于二维数组。
  • 但那些会是你的类型?我问它是因为如果那些是已知的 .net 类型或您自己的类型,您可以添加 [Serializable] 属性,那么序列化它们是最好的方法,如果是,那么我将向您展示如何序列化它
  • 这是双重类型@Gusman。是的,请。

标签: c# file hashtable


【解决方案1】:

如果您在 Hashtable 中仅存储 Doubles,则可以使用 BinaryFormatterserialize and deserialize 您的数据结构。

Hashtable DTVector = new Hashtable();

DTVector.Add("key",12);
DTVector.Add("foo",42.42);
DTVector.Add("bar",42*42);

// write the data to a file
var binformatter = new  System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
using(var fs = File.Create("c:\\temp\\vector.bin"))
{
    binformatter.Serialize(fs, DTVector);
}

// read the data from the file
Hashtable vectorDeserialized = null;
using(var fs = File.Open("c:\\temp\\vector.bin", FileMode.Open))
{
     vectorDeserialized = (Hashtable) binformatter.Deserialize(fs);
}

// show the result
foreach(DictionaryEntry entry in vectorDeserialized)
{
    Console.WriteLine("{0}={1}", entry.Key,entry.Value);
}

请记住,您添加到 Hashtable 的对象需要是可序列化的。 .Net 框架中的值类型是和其他一些类。

如果你会像这样创建自己的类:

public class SomeData
{
    public Double Value {get;set;}
}

然后你像这样向 Hashtable 添加一个实例:

DTVector.Add("key",new SomeData {Value=12});

调用 Serialize 时会出现异常:

在未标记为可序列化的程序集“blah”中键入“SomeData”。

您可以按照异常消息中的提示,将属性 Serializable 添加到您的类中

[Serializable]
public class SomeData
{
    public Double Value {get;set;}
    public override string ToString()
    {
       return String.Format("Awesome! {0}", Value );
    }
}

【讨论】:

    【解决方案2】:

    最终,我认为要能够轻松地将对象写出,它们需要可序列化。您可以使用 dotnet protobuf 实现之类的东西来更有效地存储它,而不是简单地转储到文件中。

    【讨论】:

      猜你喜欢
      • 2015-07-21
      • 2015-09-19
      • 2018-05-08
      • 1970-01-01
      • 2020-07-29
      • 2014-02-12
      • 2012-05-15
      • 1970-01-01
      • 2011-05-16
      相关资源
      最近更新 更多