使用 Json 比较 C# 对象
我想比较两个对象而不实现 Equals() 方法。
以这种方式比较它们的缺点是什么: 1.用Json序列化它们 2.比较结果
谢谢!
I want to compare two objects without implementing the Equals() method.
What are the downsides of comparing them in this way:
1. serilizing them with Json
2. comparing the results
thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
速度损失。将对象转换为 JSON 字符串然后比较它们比通过属性等于属性要慢得多。
实现
Equals()
始终是比较两个对象是否相等的最佳方法。Loss of speed. Transforming objects into JSON strings and then comparing them is much slower than doing a property by property equals.
Implementing
Equals()
is always the best way to compare two objects for equality.缺点是您需要序列化它们,这可能很慢,而且肯定比实现
Equals
慢。您还可能最终会发现需要比较的部分对象没有被序列化,因此无法获得真正的比较。
The downside is that you need to serialize them, which is potentially slow, and definitely slower than implementing
Equals
.You may also end up with part of the objects that you need to compare not being seriazlied and therefore not getting true comparison.
将对象转换为 json 的序列化过程会产生一些开销。您必须进行测试,看看开销是否适合您的情况。
除此之外,json 对象的来源也是一个问题。我见过几个不同的 json 序列化器以不同的方式格式化对象(例如,引用属性名称与不引用它们)。像这样的事情可能会给你带来不真实的结果。
There is some overhead to the serialization process to convert objects to json. You'd have to test to see if the overhead is acceptable for your situation.
That aside, the source of the json object is a concern. I've seen a couple different json serializers format objects differently (e.g. quoting property names vs. not quoting them). Things like this could yield you untrue results.
也许使用这样的类你可以完成这项工作(BsonDocument 是来自 MongoDBDriver 的类):
Maybe with a class like that you can do the work (BsonDocument is a class from MongoDBDriver):