BinaryFormatter忽略程序集版本 [英] BinaryFormatter ignore assembly version
问题描述
我具有以下方法来生成对象的哈希。效果不错!但是,当我更改程序集的版本时,即使对象相同,哈希也会发生变化。
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屋!