简体   繁体   English

比较两个已知的复杂类型对象而不使用反射

[英]Compare two known Complex type object without using reflection

I have two known Complex Object of same type or even two object of two different class having exactly same properties. 我有两个相同类型的已知复杂对象,或者甚至两个具有完全相同属性的不同类的对象。 How can I compare properties of the two object WITHOUT using reflection or manual properties comparison.? 如何在不使用反射或手动属性比较的情况下比较两个对象的属性?

Simply put, you can't... Unless the objects already implement an Equals method :-) There are no magic fairies that will compare objects in .NET . 简而言之,您将无法……除非对象已经实现了Equals方法:-)没有魔术精灵可以比较.NET中的对象。

Technically there is a third way... It goes totally against what you literally wrote, but is normally considered to be "acceptable": write a T4 template that, using reflection, generates a .cs file containing the comparator (that compares the objects using manual property comparison). 从技术上讲,还有第三种方法……完全违背了您的字面意思,但通常被认为是“可以接受的”:编写一个T4模板,该模板使用反射生成一个包含比较器(比较对象)的.cs文件。使用手动属性比较)。 The T4 is run at compile time, and the .cs generated is generated at compile time (and compiled), so there is no reflection at runtime, and there is no "human written" manual property comparison. T4在编译时运行,而生成的.cs是在编译时生成(并编译)的,因此在运行时没有任何反映,也没有“人工编写的”手动属性比较。

Note that doing this T4 template correctly is very complex... It is a project inside a project! 请注意,正确执行此T4模板非常复杂...这是项目中的一个项目!
There are many ways to do it, each one with its pitfalls. 有很多方法可以做到,每种方法都有其缺陷。 Just deciding what to compare (fields or properties) is a problem enough. 仅确定要比较的内容(字段或属性)就足够了。 And for the fields/properties, do you want to compare everything with an option to exclude something, or nothing with an option to include what you really want to compare? 对于字段/属性,您是否想将所有内容与一个选项进行比较以排除某些内容,或者不进行任何选择而将您真正想要比较的内容进行比较? Then deciding what to do with collections (do you want to compare their elements?). 然后决定如何处理集合(要比较它们的元素吗?)。 Many decisions to take! 要做很多决定!

As xanatos says above, you cannot, however there are a bunch of widgets which have done this for you. 如xanatos上面所述,您不能,但是有许多小部件可以为您完成此操作。

For example: https://github.com/StevenGilligan/AutoCompare 例如: https : //github.com/StevenGilligan/AutoCompare

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM