【发布时间】:2011-05-10 17:23:43
【问题描述】:
我正在尝试序列化一个 Hashset,但我没有运气。每当我尝试打开序列化数据时,我都会得到一个空的 HashSet。但是,列表工作正常。示例代码:
[Serializable()]
public class MyClass : ISerializable
{
public MyClass(SerializationInfo info, StreamingContext ctxt)
{
HashSet<string> hashset = (HashSet<string>)info.GetValue("hashset", typeof(HashSet<string>));
List<string> list = (List<string>)info.GetValue("list", typeof(List<string>));
Console.WriteLine("Printing Hashset:");
foreach (string line in hashset)
{
Console.WriteLine(line);
}
Console.WriteLine("Printing List:");
foreach (string line in list)
{
Console.WriteLine(line);
}
}
public void GetObjectData(SerializationInfo info, StreamingContext ctxt)
{
HashSet<string> hashset = new HashSet<string>();
hashset.Add("One");
hashset.Add("Two");
hashset.Add("Three");
info.AddValue("hashset", hashset);
List<string> list = new List<string>();
list.Add("One");
list.Add("Two");
list.Add("Three");
info.AddValue("list", list);
}
}
运行时会打印出来:
Printing Hashset:
Printing List:
One
Two
Three
所以 List 工作正常,但 HashSet 却是空的。有点卡住 - 谁能看到我做错了什么?谢谢
【问题讨论】:
-
为什么要自己做序列化?为什么不使用 DataContractSerializer ?
标签: c# .net hash c#-4.0 hashset