在字典中序列化HashSet

时间:2012-10-12 07:18:16

标签: c# .net serialization hashset

我遇到与Serializing a HashSet

类似的问题

我有一个类型为Dictionary<String,HashSet<T>>

的成员

当我使用BinaryFormatter序列化Object,然后反序列化它时,它会变空。

我不知道如何或在何处调用here发布的变通方法。

任何提示?提前谢谢。

编辑: 我试图将hashset转换为一个列表,作为另一个线程建议的注释之一。

对象看起来像这样:

public class THashSet : HashSet<T> , ISerializable
{

    public THashSet(SerializationInfo info, StreamingContext context)
    {
        var list = (List<T>)info.GetValue("hashset", typeof(List<T>));     
        foreach (T t in list)
            this.Add(t);
    }

    public override void GetObjectData(SerializationInfo info,StreamingContext context)
    {
        info.AddValue("hashset", this.ToList<T>());
    }

当反序列化包含THashSet的对象(并且调用构造函数)时,正确地恢复列表,正​​如我在调试器中看到的那样。

但在序列化程序完成后,该对象只包含一个空的hashset。

1 个答案:

答案 0 :(得分:1)

假设您的T对象没有覆盖方法GetHashCode和Equals。你需要这样做。

UPD:全部取决于你的对象实现。并且对象并不像你说的那么容易。你的作品,对象:

[Serializable]
public class DataClass
{       
    public DataClass()
    {
    }

    public DataClass(string name, string description)
    {
        Name = name;
        Description = description;

        this.Dictionary = new Dictionary<string, HashSet<DataClass>>();
    }

    public string Name { get; set; }

    public string Description { get; set; }

    public Dictionary<string, HashSet<DataClass>> Dictionary { get; set; }
}

序列化/反序列化代码:

DataClass dataClass = new DataClass("name", "descr");
dataClass.Dictionary.Add("key1", new HashSet<DataClass>() { new DataClass("sample11", "descr11"), new DataClass("sample12", "descr12") });
dataClass.Dictionary.Add("key2", new HashSet<DataClass>() { new DataClass("sample21", "descr21"), new DataClass("sample22", "descr22") });
dataClass.Dictionary.Add("key3", new HashSet<DataClass>() { new DataClass("sample31", "descr31"), new DataClass("sample32", "descr32") });

byte[] serialized;
var formatter = new BinaryFormatter();

using (MemoryStream stream = new MemoryStream())
{
    formatter.Serialize(stream, dataClass);
    serialized = stream.ToArray();
}
using (MemoryStream streamDeserial = new MemoryStream())
{
    streamDeserial.Write(serialized, 0, serialized.Length);
    streamDeserial.Seek(0, SeekOrigin.Begin);
    var dictDeserial = formatter.Deserialize(streamDeserial) as DataClass;
} 

此代码效果很好。