比较运算符的重载

比较运算符的重载

比较运算符的重载

using System;

namespace 比较运算符的重载
{
    class Program
    {
        static void Main(string[] args)
        {
            //Console.WriteLine("Hello World!");       
            Vector vec1,vec2,vec3;
            vec1 = new Vector(3.0,3.0,-10.0);
            vec2 = new Vector(3.0,3.0,-10.0);
            vec3 = new Vector(2.0,3.0,6.0);
            System.Console.WriteLine($"vec1 == vec2 returns {vec1 == vec2}");
            System.Console.WriteLine($"vec1 == vec3 returns {vec1 == vec3}");
            System.Console.WriteLine($"vec2 == vec3 returns {vec2 == vec3}");
            System.Console.WriteLine();
            System.Console.WriteLine($"vec1 != vec2 returns {vec1 != vec2}");
            System.Console.WriteLine($"vec1 != vec3 returns {vec1 != vec3}");
            System.Console.WriteLine($"vec2 != vec3 returns {vec2 != vec3}");

            //生成如下结果
            // vec1 == vec2 returns True
            // vec1 == vec3 returns False
            // vec2 == vec3 returns False

            // vec1 != vec2 returns False
            // vec1 != vec3 returns True
            // vec2 != vec3 returns True
        }
    }

        struct Vector{
        public double X{get;}
        public double Y{get;}
        public double Z{get;}
        public Vector(double x,double y,double z){
            X = x;
            Y = y;
            Z = z;

        }
        public Vector(Vector vector){
            X = vector.X;
            Y = vector.Y;
            Z = vector.Z;

        }
        public override string ToString()=>$"({X},{Y},{Z})";

        public static bool operator == (Vector left,Vector right)
        {
            if(object.ReferenceEquals(left,right)) return true;
            return left.X == right.X &&left.Y == right.Y && left.Z == right.Z;

        }

       //还需要重载!=
        public static bool operator != (Vector left,Vector right)=>!(left == right);
        //现在重写Equals和GetHashCode方法。这些方法应该总是在重写==运算符时进行重写,否则编译器会报错。
        public override bool Equals(object obj)
        {
            if(obj == null) return false;
            return this == (Vector)obj;
        }

        public override int GetHashCode()=>X.GetHashCode() ^ Y.GetHashCode() ^ Z.GetHashCode();

        //有了以上所有代码,就可以实现该方法。
        public bool Equals(Vector vector)=>this == vector;

    }
}
01-09 17:19