C#-运算符重载

我的未来我决定 提交于 2020-01-07 17:57:47

【推荐】2019 Java 开发者跳槽指南.pdf(吐血整理) >>>

通过运算符重载,可以对我们设计的类使用标准的运算符,例如+、-等。这称为重载,因为在使用特定的参数类型时,我们为这些运算符提供了自己的实现代码,其方式与重载方法相同,也是为同名方法提供不同的参数。运算重载符定义>,同样需要定义<;同样定义运算符==,!=也需要定义,同时最好重写GetHashCode()方法和Equals(Object o)方法。

class Time
    {
        private int hour;
        private int min;

        public Time(int hour, int min)
        {
            this.hour = hour;
            this.min = min;
        }
        public void Add(Time t)
        {
            this.hour = this.hour + t.hour + (t.min + this.min) / 60;
            this.min = (this.min + min) % 60;
        }
        public override string ToString()
        {
            return string.Format("{0,2}:{1,2}", hour, min);
        }
        public override bool Equals(object obj)
        {
            return this == (Time)obj;
        }
        public override int GetHashCode()
        {
            return this.GetTotalMins();
            //return 1;
        }
        public int GetTotalMins()
        {
            return hour * 60 + min;
        }
        public static Time operator +(Time t1, Time t2)
        {
            Time result = new Time(0, 0);
            result.hour = t1.hour + t2.hour + (t1.min + t2.min) / 60;
            result.min = (t1.min + t2.min) % 60;
            return result;
        }
        public static bool operator >(Time t1, Time t2)
        {
            if (t1.GetTotalMins() > t2.GetTotalMins())
                return true;
            return false;
        }
        public static bool operator <(Time t1, Time t2)
        {
            if (t1.GetTotalMins() < t2.GetTotalMins())
                return true;
            return false;
        }
        public static bool operator >=(Time t1, Time t2)
        {
            return !(t1 < t2);
        }
        public static bool operator <=(Time t1, Time t2)
        {
            return !(t1 > t2);
        }
        public static bool operator ==(Time t1, Time t2)
        {
            return t1.GetTotalMins() == t2.GetTotalMins();
        }
        public static bool operator !=(Time t1, Time t2)
        {
            return !(t1==t2);
        }      
    }

 

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!