我想序列化具有自定义 IEqualityComparer
的字典。
我试过使用 DataContractSerializer
但我无法让 Comparer
被序列化。
由于 this,我无法使用 BinaryFormatter
.
我总是可以做这样的事情:
var myDictionary = new MyDictionary(deserializedDictionary, myComparer);
但这意味着我需要字典使用的内存的两倍。
最佳答案
为什么自定义Comparer还要序列化? 这是一个适合我的测试用例。
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 ); } }
关于c# - 使用自定义 IEqualityComparer 对字典进行 XML 序列化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/366541/