BinaryFormatter 忽略程序集版本 [英] BinaryFormatter ignore assembly version

查看:37
本文介绍了BinaryFormatter 忽略程序集版本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下方法来生成对象的散列.它工作得很好!但是当我更改程序集的版本时,即使对象相同,哈希值也会发生变化.

I have the following method to generate a hash of an object. It works pretty good! But when I change the version of the assembly, the hash is changing even when the object is the same.

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));
}

怎么可能忽略程序集版本?

How is it possible to ignore the assembly version?

推荐答案

但是当我更改程序集的版本时,即使对象相同,哈希值也会发生变化.

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

是的,这是使用 BinaryFormatter 时的预期行为......它不保证创建相同的输出 - 尤其,因为它包含完整的类型信息(包括版本) 几乎可以保证版本之间会发生变化.

yes, that is expected behaviour when using BinaryFormatter... it does not guarantee to create the same output - and especially since it includes full type information (including version) it is pretty much guaranteed to change between versions.

我会考虑使用不包含类型信息的序列化程序;XmlSerializer、Json.NET 或 protobuf-net 会跃入脑海.

I would consider using a serializer that doesn't include type information; XmlSerializer, Json.NET or protobuf-net would leap to mind.

这篇关于BinaryFormatter 忽略程序集版本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆