//IEquatable Readme //The IEquatable.Equals method is very similar to Object.Equals. However, IEquatable.Equals is type-safe and generic—requiring no boxing and unboxing. //IEquatable.Equals方法非常类似于Object.Equals,然而IEquatable.Equals是安全类型和类,不需要装箱和拆箱。 //At first glance, the IEquatable interface appears very similar to the IComparable interface. //乍看,IEquatable 接口显现非常类似于IComparable接口。 //But, whereas IEquatable returns a bool representing only whether the instances are equal or not, IComparable returns an int indicating how the instances differ—whether smaller, equal or larger. //但是 然而IEquatable 返回一个布尔表示这个实例是否相等,IComparable返回一个整型,这个实例不同于是否是Smaller,Equal,Larger. class Program { staticvoid Main(string[] args) { Vector va =new Vector(1.5,1.5,1.5); Vector vb =new Vector(1.5,1.5,1.5); //The reason for the first result is because the == compares the value stored in the variables myVA and myVB. //Because these represent instances of classes they are reference types, //so the values are memory addresses of where the actual object is stored in the heap. //Therefore they can never be identical unless they actually point to the same object. if(va == vb) { Console.WriteLine("va == vb"); } else { Console.WriteLine("va != vb"); } /**////The second result is from the Equals() method, this returns the correct result as the class has compared the actual values. if(va.Equals(vb)) { Console.WriteLine("va == vb IEquatable"); } else { Console.WriteLine("va != vb IEquatable"); } } } class Vector : IEquatable<Vector> { privatedouble x; publicdouble getX() { return x; } privatedouble y; publicdouble getY() { return y; } privatedouble z; publicdouble getZ() { return z; } public Vector(double x, double y, double z) { this.x = x; this.y = y; this.z = z; } IEquatable Members#region IEquatable<Vector> Members publicbool Equals(Vector other) { Boolean result =false; if (this.x.Equals(other.getX()) && this.y.Equals(other.getY()) && this.z.Equals(other.getZ())) { result =true; } return result; } #endregion }