Overriding peers for classes with many properties in C #

I have a number of data classes that have more than 25 properties of different types of values ​​(and this may change in the future as requirements change). I would like to redefine equal values, mainly for unit testing purposes.

Currently, the only way I know how to do this is to verify that each property is actually hardcoded. This seems bad for two reasons: firstly, I will need to write a lot of code to check 25 properties for equality - secondly, if a property is added in one of the classes later, the Equals method does not check this, and most likely it will remain undetected and lead to problems in the future.

Because Equals typically checks for class properties, there must be a way to dynamically compare the properties of the classes being compared, which ensures that the property modifies the class without leading to an incorrect implementation of Equals. Is there any way to do this?

+5
source share
5 answers

you could write something like this using reflection - but that would be very slow. I would adhere to excellent equals, but thought about how much you really need as an equal. I usually check for immutable parts (like Id) for equality and just ignore mutable fields, and I think this is good practice.

+4
source

. . # !

+1

, , .

, , . , , , , TypeDescriptor .

+1

AOP Frameworks. , , , , , , .

+1

Maybe T4 can help you. With it, you can generate code with one click. As part of this function, you can use the slow reflection mechanism to create a hard-coded GetHashCode () function that will be called at run time. For a first look at the T4, check out the Scotts blog about it. Or just try searching Text Template Transformation Toolkitwith your favorite search engine.

+1
source

All Articles