tailieunhanh - accelerated c# 2010 trey nash phần 9

Tham khảo tài liệu 'accelerated c# 2010 trey nash phần 9', công nghệ thông tin, kỹ thuật lập trình phục vụ nhu cầu học tập, nghiên cứu và làm việc hiệu quả | CHAPTER 13 IN SEARCH OF C CANONICAL FORMS You ve seen how equality tests on references to objects test identity by default. However there might be times when an identity equivalence test makes no sense. Consider an immutable object that represents a complex number public class ComplexNumber . public ComplexNumber int real int imaginary . real imaginary private int real private int imaginary public class EntryPoint static void Main . ComplexNumber referenceA new ComplexNumber 1 2 ComplexNumber referenceB new ComplexNumber 1 2 Result of Equality is 0 referenceA referenceB The output from that code looks like this Result of Equality is False Figure 13-2 shows the diagram representing the in-memory layout of the references. Figure 13-2. References to ComplexNumber This is the expected result based upon the default meaning of equality between references. However this is hardly intuitive to the user of these ComplexNumber objects. It would make better sense for the comparison of the two references in the diagram to return true because the values of the two objects are the same. To achieve such a result you need to provide a custom implementation of equality for these objects. I ll show how to do that shortly but first let s quickly discuss what value equality means. 453 CHAPTER 13 IN SEARCH OF C CANONICAL FORMS Value Equality From the preceding section it should be obvious what value equality means. Equality of two values is true when the actual values of the fields representing the state of the object or value are equivalent. In the ComplexNumber example from the previous section value equality is true when the values for the real and imaginary fields are equivalent between two instances of the class. In the CLR and thus in C this is exactly what equality means for value types defined as structs. Value types derive from and overrides the method. sometimes .