3.1.4

3.1.4 #

解答 #

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

Time 类型包含时分秒三个 int 变量,同时实现 IComparable 接口。

Event 类型只包含事件的名称,相当于对 string 做了一个封装。

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

代码 #

Time 类

public class Time : IComparable<Time>
{
    public int Hour { get; init; }
    public int Minute { get; init; }
    public int Second { get; init; }

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

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

    public int CompareTo(Time other)
    {
        var result = Hour.CompareTo(other.Hour);
        if (result == 0)
            result = Minute.CompareTo(other.Minute);
        if (result == 0)
            result = 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()
    {
        var result = 1;
        result += Hour;
        result *= 31;
        result += Minute;
        result *= 31;
        result += Second;
        return result;
    }

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

Event 类

public class Event
{
    public string EventMessage { get; set; }

    public Event() : this(null) { }

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

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

另请参阅 #

SymbolTable 库