XML serialization of a Dictionary with a custom IEqualityComparer

前端 未结 2 473
有刺的猬
有刺的猬 2021-01-20 17:12

I want to serialize a Dictionary that has a custom IEqualityComparer.

I\'ve tried using DataContractSerializer but I can\'t get the C

2条回答
  •  独厮守ぢ
    2021-01-20 18:06

    Why does the custom Comparer even need to be serialized? Here is a test case that works for me.

    using System;
    using System.Collections.Generic;
    using System.Runtime.Serialization;
    using System.IO;
    
    public class MyKey {
        public string Name { get; set; }
        public string Id { get; set; }
    }
    
    public class MyKeyComparer :IEqualityComparer {
        public bool Equals( MyKey x, MyKey y ) {
            return x.Id.Equals( y.Id ) ;
        }
        public int GetHashCode( MyKey obj ) {
            if( obj == null ) 
                throw new ArgumentNullException();
    
            return ((MyKey)obj).Id.GetHashCode();
        }
    }
    
    public class MyDictionary :Dictionary {
        public MyDictionary()
            :base( new MyKeyComparer() )
        {}
    }
    
    class Program {
        static void Main( string[] args ) {
            var myDictionary = new MyDictionary();
            myDictionary.Add( new MyKey() { Name = "MyName1", Id = "MyId1" }, "MyData1" );
            myDictionary.Add( new MyKey() { Name = "MyName2", Id = "MyId2" }, "MyData2" );
    
            var ser = new DataContractSerializer( typeof( MyDictionary ) );
    
            using( FileStream writer = new FileStream( "Test.Xml", FileMode.Create ) )
                ser.WriteObject( writer, myDictionary );
    
            using( FileStream reader = new FileStream( "Test.Xml", FileMode.Open ) )
                myDictionary = (MyDictionary)ser.ReadObject( reader );
        }
    }
    
    

提交回复
热议问题