开发者

Compare two object from the same class with tons of fields

I got two objects from the same class and I need to compare them field by field. The problem is that they have close to hundred fields and it would be helluva work to write that by hand.

Do you know any way to do that the easier way? Reflections in Java could be a solution, but yet it seems to 开发者_开发知识库me like a hack. And I seek a C# solution after all.


Two ideas:

  1. Use reflection (it is available in C#) runtime and loop over the fields of the clas comparing them. If you want to be able to exclude certain fields you could do that by creating an attribute class and mark the fields you don't want to compare with that attribute.

  2. Use reflection to loop over the fields in the same way and generate the required comparison code. This way you will have "real" code but won't have to write and maintain it yourself. Attributes can be used to fine-tune the comparison code generated.


The best is to refactor your code, hundred fields is way to mush.

If you can't because is a legacy code find out which attribute make them equals.


If you're lucky, you'll identify one or two properties that are unique for the instance -- especially likely if you class represents a database entity -- and you will only have to compare those unique properties.


Use Regular Expression find and replace. It's a pain when you have to add fields *(removed ones get you a compile error), but you get the benefit of having compiled code.

Really, though, consider splitting the class up. If there's 100 fields, can they be grouped in component classes? 100 members is a lot of mess to have to manage.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜