我有一个具有字符串和散列表的类.hash表包含每个键属性的键(字符串)值和位图文件的集合。 我如何将其序列化为二进制文件?
public void SerializeObject(List<Poem> poems)
{
using (Stream stream = File.Open("data.bin", FileMode.Create))
{
BinaryFormatter bin = new BinaryFormatter();
bin.Serialize(stream, poems);
}
}
public List<Poem> DeSerializeObject()
{
List<Poem> poems1;
using (Stream stream = File.Open("data.bin", FileMode.Open))
{
BinaryFormatter bin = new BinaryFormatter();
var lizards2 = (List<Poem>)bin.Deserialize(stream);
poems1 = (List<Poem>)lizards2;
}
return poems1;
}
// poem class
[Serializable()]
public class Poem
{
string poemName;
Hashtable poemContent; contains set of keys(strings) , values(bitmap)//
public Poem() {
poemContent = new Hashtable();
}
public string PoemName
{
get { return poemName; }
set { poemName = value; }
}
public Hashtable PoemContent
{
get { return poemContent; }
set { poemContent = value; }
}}
但这总会产生错误。
答案 0 :(得分:1)
我可以毫无错误地运行您的代码。致电代码:
SerializeObject(new List<Poem>
{
new Poem
{
PoemContent = new Hashtable {{"Tag", new System.Drawing.Bitmap(1, 1)}},
PoemName = "Name"
}
});
var poems2 = DeserializeObject();
您看到的错误是什么?是编译器错误还是运行时异常?我可以在诗歌的示例列表中毫无问题地运行此代码。顺便说一句,我建议使用Dictionary<K,V>
代替HashTable
。