开发者

deserialize SortedSet : why items need to implement IComparable?

I have de folowing classes :

[DataContract]
public class MyProject 
{
    [DataMember(Name = "Branches")]
    private SortedSet<ModuleFilter> branches = new SortedSet<ModuleFilter>(new ModuleFilterComparer());

    [DataMember(Name="VbuildFilePath")]
    private string buildprogram = null;
}

I can serialize it to a file with :

DataContractSerializer x = new DataContractSerializer(p.GetType());
using (System.Xml.XmlWriter writer = System.Xml.XmlWriter.Create(p.GetFilePath()))
{
    x.WriteObject(writer, p);
}

But when I try to read it back with the folowing piece of code, it fails unless I add a dummy implementation of IComparable to the ModuleFilter obje开发者_JS百科ct

DataContractSerializer x = new DataContractSerializer(typeof(MyProject));
using (System.Xml.XmlReader reader = System.Xml.XmlReader.Create(filePath))
{
    p = (MyProject)x.ReadObject(reader);
}

Why does not the deserializer use the provided IComparer of the SortedSet member ?

Thank you


It is because DataContractSerializer uses default constructor of SortedSet to initialize field.

Solution 1: recreate field after deserialization with needed comparer



    [DataContract]
    public class MyProject : IDeserializationCallback
    {
      //...
      void IDeserializationCallback.OnDeserialization(Object sender)
      {
        branches = new SortedSet<ModuleFilter>(branches, new ModuleFilterComparer());
      }
    }


Solution 2: use your own sorted set implementation instead of SortedSet<ModuleFilter>



     public class ModuleFilterSortedSet : SortedSet<ModuleFilter>
        {
            public ModuleFilterSortedSet()
                : base(new ModuleFilterComparer())
            {
            }

            public ModuleFilterSortedSet(IComparer<ModuleFilter> comparer) 
                : base(comparer)
            {
            }
        }

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜