编程语言
首页 > 编程语言> > c# – BinaryFormatter忽略汇编版本

c# – BinaryFormatter忽略汇编版本

作者:互联网

我有以下方法来生成对象的哈希.它的效果非常好!但是当我更改程序集的版本时,即使对象相同,哈希也会发生变化.

public static string GetHash(Object item)
{
    MemoryStream memoryStream = new MemoryStream();
    BinaryFormatter binaryFormatter = new BinaryFormatter();
    binaryFormatter.Serialize(memoryStream, item);
    binaryFormatter.AssemblyFormat = FormatterAssemblyStyle.Simple;

    HashAlgorithm hashAlgorithm = new MD5CryptoServiceProvider();
    memoryStream.Seek(0, SeekOrigin.Begin);

    return Convert.ToBase64String(hashAlgorithm.ComputeHash(memoryStream));
}

如何忽略装配版本?

解决方法:

But when I change the version of the assembly, the hash is changing even when the object is the same.

是的,这是使用BinaryFormatter时的预期行为…它不保证创建相同的输出 – 特别是因为它包含完整类型信息(包括版本),所以几乎可以保证在版本之间进行更改.

我会考虑使用不包含类型信息的序列化程序; XmlSerializer,Json.NET或protobuf-net将会浮现在脑海中.

标签:c,serialization,net-assembly,binaryformatter
来源: https://codeday.me/bug/20190529/1176454.html