通过比较它们的序列化字节数组来比较类的两个实例是否可靠? [英] Is it reliable to compare two instances of a class by comparing their serialized byte arrays?

查看:142
本文介绍了通过比较它们的序列化字节数组来比较类的两个实例是否可靠?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定类的两个实例,通过首先对它们进行序列化,然后比较字节数组(或者可能的数组的散列)来比较它们是一个好的可靠的做法。
这些对象可能具有复杂的层次属性,但是序列化应该根据需要进行深度。



比较我的意思是确保所有属性的原始类型具有相等的值,复杂类型的属性具有与原始类型相等的属性等。对于集合属性,它们应该彼此相等:相等的元素,相同的位置:

  {'a','b','c'}!= {'a','c','b'} 



{new Customer {Id = 2,Name =abc},new Customer {Id = 3,Name =def}}
!=
{new Customer {Id = 3 ,Name =def},new Customer {Id = 2,Name =abc}}

  {new Customer {Id = 2,Name =abc},new Customer {Id = 3,Name = def}} 
==
{new Customer {Id = 2,Name =abc},new Customer {Id = 3,Name =def}}

通过序列化我的意思是标准的.NET二进制格式化。



解决方案

您要求保证序列化表示匹配。这将是非常困难的,BinaryFormatter是一个复杂的类。特别是具有对齐填充的序列化结构可能是一个潜在的问题。



更简单的是提供一个不匹配的示例。 System.Decimal对于诸如0.01M和0.010M的值具有不同的字节模式。它的操作符==()会说它们是相等的,它的序列化字节[]不会。


Given two instances of a class, is it a good and reliable practice to compare them by serializaing them first and then comparing byte arrays (or possibly hashes of arrays). These objects might have complex hierarchical properties but serialization should go as deep as required.

By comparison I mean the process of making sure that all propertis of primitive types have equal values, properties of complex types have equal properties of primitive types, etc. As for collection properties, they should be equal to each other: equal elements, same positions:

{'a','b','c'} != {'a','c','b'}



 {new Customer{Id=2, Name="abc"}, new Customer {Id=3, Name="def"}} 
    !=
 {new Customer{Id=3, Name="def"}, new Customer {Id=2, Name="abc"}}

but

 {new Customer{Id=2, Name="abc"}, new Customer {Id=3, Name="def"}}
    ==
 {new Customer{Id=2, Name="abc"}, new Customer {Id=3, Name="def"}}

And by serialization I mean standard .NET binary formatter.

Thanks.

解决方案

You are asking for a guarantee that the serialized representation will match. That's going to be awfully hard to come by, BinaryFormatter is a complicated class. Particularly serialized structures that have alignment padding could be a potential problem.

What's much simpler is to provide an example where it won't match. System.Decimal has different byte patterns for values like 0.01M and 0.010M. Its operator==() will say they are equal, its serialized byte[] won't.

这篇关于通过比较它们的序列化字节数组来比较类的两个实例是否可靠?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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