3.1.4

上次更新:2019-04-17
发现了题解错误/代码缺陷/排版问题?请点这里:如何:提交反馈

解答

利用 Time 类型记录时间,用 Event 来记录事件内容。

Time 类型包含时分秒三个 int 变量,同时实现 IComparable 接口。
Event 类型只包含事件的名称,相当于对 string 做了一个封装。

随后以 Time 为键类型,Event 为值类型,利用上一题编写的有序符号表进行操作。

代码

Time 类

using System;
using System.Text;

namespace _3._1._4
{
    /// <summary>
    /// 时间类。
    /// </summary>
    public class Time : IComparable<Time>
    {
        public int Hour { get; set; }
        public int Minute { get; set; }
        public int Second { get; set; }

        public Time() : this(0, 0, 0) { }

        public Time(int hour, int minute, int second)
        {
            this.Hour = hour;
            this.Minute = minute;
            this.Second = second;
        }

        public int CompareTo(Time other)
        {
            int result = this.Hour.CompareTo(other.Hour);
            if (result == 0)
                result = this.Minute.CompareTo(other.Minute);
            if (result == 0)
                result = this.Second.CompareTo(other.Second);
            return result;
        }

        public override bool Equals(object obj)
        {
            if (this == obj)
                return true;
            return CompareTo((Time)obj) == 0;
        }

        public override int GetHashCode()
        {
            int result = 1;
            result += this.Hour;
            result *= 31;
            result += this.Minute;
            result *= 31;
            result += this.Second;
            return result;
        }

        public override string ToString()
        {
            StringBuilder sb = new StringBuilder();
            sb.Append(this.Hour < 10 ? "0" + this.Hour : this.Hour.ToString());
            sb.Append(":");
            sb.Append(this.Minute < 10 ? "0" + this.Minute : this.Minute.ToString());
            sb.Append(":");
            sb.Append(this.Second < 10 ? "0" + this.Second : this.Second.ToString());
            return sb.ToString();
        }
    }
}

Event 类

namespace _3._1._4
{
    public class Event
    {
        public string EventMessage { get; set; }

        public Event() : this(null) { }

        public Event(string message)
        {
            this.EventMessage = message;
        }

        public override string ToString()
        {
            return this.EventMessage;
        }
    }
}

另请参阅

SymbolTable 库

上一题 下一题