c# - 使用自定义 IEqualityComparer 对字典进行 XML 序列化

标签 c# serialization dictionary xml-serialization

我想序列化具有自定义 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/

相关文章:

c# - 转到文本编辑器中的行

c# - 枚举所有正在运行的数据库

java - 如何使用 Kryo 序列化 Multimap?

Java GZip 一个对象并使用 MappedByteBuffer 对其进行序列化

java - 获取 Jersey 反序列化为子类

c++ - 如何使用 std::variant 打印映射键/值?

c# - CommandBarButton 图标变得黑色背景

c# - 如何以编程方式替换 .NET 程序集中的嵌入式资源?

java list<map> 具有重复值

dictionary - 如何安全地允许当前访问go中的嵌套 map ?