简体   繁体   中英

Is reflection the better way to compare two objects of the same type?

Background:

I have 2 instances of an object of the same type. One object is populated with the configuration of a device I'm connected to, the other object is populated with a version of the configuration that I've stored on my hard drive.

The user can alter either, so I'd like to compare them and present the differences to the user.

Each object contains a number of ViewModel properties, all of which extend ViewModelBase , which are the ones I want to compare.

Question:

Is a better way to do this than what I'm about to propose.

I'm thinking of using Reflection to inspect each property in my objects, and for each that extend ViewModelBase , I'll loop through each of those properties. For any that are different, I'll put the name and value into a list and then present that to the user.

Rather than inventing this wheel, I'm wondering if this is this a problem that's been solved before? Is there a better way for it to be done?

Depending on the amount of properties to be compared, manual checking would be the more efficient option. However, if you have lots of properties or want the check to be dynamic (ie you just add new properties and it automagically works), then I think Reflection is the way to go here.

Why not just implement the equals operator for your type?

http://msdn.microsoft.com/en-us/library/ms173147(v=vs.80).aspx

Edit: Having read more carefully I see what you're actually asking is what the most efficient way of doing the actual comparison is.

Doing it via reflection saves on code but is slower. Doing it with lots of manual comparions is fairly quick but more code.

If you are fairly determent and lazy in the good way. You can mix benefits of both solutions. With help of tool like cci you can emit method that compares properties. The beauty of this is that your reflection code will be executed on compile time leaving you with strait forward method to execute at runtime. This allows you to change models as you see fit and not worry about comparison code. There is a down side to this and that is learning cci which is quite challenging.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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