Overriding Equals for classes with many properties in C#
I have a number of data classes that have over 25 properties of different value types (and this may change in the future as requirements change). I would like to override equals, mostly for unit testing purposes.
Currently, the only way I know how to do this is to actually test for equality of each property hard coded. This seems bad for two reasons - first, I will have to write a lot of code to test 25 propert开发者_如何转开发ies for equality - second, if a property in one of the classes is added at a later point in time, the Equals method will not check that, and most likely this will go unnoticed and lead to problems down the road.
Since Equals usually checks for the properties of classes, there should be a way to dynamically compare the properties of the classes being compared, which ensures that property changes to a class don't result in an incorrect implementation of Equals. Is there a way to do this?
you could write something like this using reflection - but this would be very slow. I would stick with overriding equals but think about which part you really need for equal. I usually only check the immutable parts (like Id) for equality and just ignore the mutable fields and I think this is a good practice.
Try using reflection to compare the properties. See Comparing object properties in c# for more info!
If your class is an entity, it should have a property which allows you to uniquely identify each instance.
If your class is implemented as a value type, you'll have to check for equality by checking each property. In the latter case, in order to prevent tedious work, you could make use of reflection to get all properties of the class at runtime, retrieve the value and use the TypeDescriptor classes to compare the values.
You can use some AOP Frameworks. If the properties you're goona to compare are much more then those ones you gonna to avoid, mark the properties to skip with special custom attribute.
Maybe T4 can help you out. With it you can generate code at a click. Within this function you can then use the slow reflection mechanism to create a hard-coded GetHashCode() function that will be called at runtime. For a first look into T4 take a look at Scotts blog about it. Or simply try searching for Text Template Transformation Toolkit
with your favorite search engine.
精彩评论