如何将哈希表写入文件?
How to write a Hashtable into the file?
如何在不知道的情况下将哈希表写入文件
里面有什么?!
Hashtable DTVector = new Hashtable();
只需将其存储到文件中,然后读取它并再次创建一个哈希表。
最终我认为为了能够轻松地写出对象,它们需要是可序列化的。您可以使用诸如 dotnet protobuf 实现之类的东西来更有效地存储它,而不仅仅是简单地转储到文件中。
如果您在哈希表中只存储双打,您可以使用 BinaryFormatter to serialize 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);
}
请记住,您添加到哈希表中的对象需要是可序列化的。 .Net 框架中的值类型是和其他一些 classes.
如果您像这样创建自己的 class:
public class SomeData
{
public Double Value {get;set;}
}
然后像这样向哈希表添加一个实例:
DTVector.Add("key",new SomeData {Value=12});
调用 Serialize 时会遇到异常:
Type 'SomeData' in Assembly 'blah' not marked as serializable.
您可以通过将属性 Serializable 添加到您的 class
来遵循异常消息中所述的提示
[Serializable]
public class SomeData
{
public Double Value {get;set;}
public override string ToString()
{
return String.Format("Awesome! {0}", Value );
}
}
如何在不知道的情况下将哈希表写入文件 里面有什么?!
Hashtable DTVector = new Hashtable();
只需将其存储到文件中,然后读取它并再次创建一个哈希表。
最终我认为为了能够轻松地写出对象,它们需要是可序列化的。您可以使用诸如 dotnet protobuf 实现之类的东西来更有效地存储它,而不仅仅是简单地转储到文件中。
如果您在哈希表中只存储双打,您可以使用 BinaryFormatter to serialize 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);
}
请记住,您添加到哈希表中的对象需要是可序列化的。 .Net 框架中的值类型是和其他一些 classes.
如果您像这样创建自己的 class:
public class SomeData
{
public Double Value {get;set;}
}
然后像这样向哈希表添加一个实例:
DTVector.Add("key",new SomeData {Value=12});
调用 Serialize 时会遇到异常:
Type 'SomeData' in Assembly 'blah' not marked as serializable.
您可以通过将属性 Serializable 添加到您的 class
来遵循异常消息中所述的提示[Serializable]
public class SomeData
{
public Double Value {get;set;}
public override string ToString()
{
return String.Format("Awesome! {0}", Value );
}
}