将 Int 转换为 String 以显示时间

Converting Int to String to display time

帮助我解决我的代码问题。我正在尝试使用 ToString() 方法将 int 格式转换为 time 格式。当我 运行 时,我得到 09:100。我还能做什么,尤其是使用 getterssetters?

public struct Time
{

    public int hours;
    public int minutes;

    public Time(int hh, int mm)
    {
        this.hours = hh;
        this.minutes = mm;
    }

    public int hh { get { return hours; } set { hours = value % 60; } }
    public int mm { get { return minutes; } set { minutes = value % 60; } }

    public override string ToString()
    {
        return String.Format("{0:00}:{1:00}", hh, mm);

    }

    public static implicit operator Time(int t)
    {

        int hours = (int)t / 60;
        int minutes = t % 60;

        return new Time(hours, minutes);

    }

    public static explicit operator int(Time t)
    {

        return t.hours * 60 + t.minutes;
    }
    public static Time operator +(Time t1, int num)
    {

        int total = t1.hh * 60 + t1.mm + num;
        int h = (int)(total / 60) % 24,
            m = total % 60;
        return new Time(h, m);
    }

    public int Minutes { get { return minutes; } set { minutes = value % 60; } }

    class Program
    {
        static void Main(string[] args)
        {
            Time t1 = new Time(9, 30);
            Time t2 = t1;
            t1.minutes = 100;
            Console.WriteLine("The time is: \nt1={0}  \nt2={1} ", t1, t2);
            Time t3 = t1 + 45;
        }
    }
}

在主要方法中将 t1.minutes = 100; 更改为 t1.Minutes = 100;
代码将如下所示:

public struct Time
{

private int hours;
private int minutes;

public Time(int hh, int mm)
{
    this.hours = hh;
    this.minutes = mm;
}

public int hh { get { return hours; } set { hours = value % 60; } }
public int mm { get { return minutes; } set { minutes = value % 60; } }

public override string ToString()
{
    return String.Format("{0:00}:{1:00}", hh, mm);
}

public static implicit operator Time(int t)
{
    int hours = (int)t / 60;
    int minutes = t % 60;
    return new Time(hours, minutes);
}

public static explicit operator int(Time t)
{
    return t.hours * 60 + t.minutes;
}
public static Time operator +(Time t1, int num)
{
    int total = t1.hh * 60 + t1.mm + num;
    int h = (int)(total / 60) % 24,
        m = total % 60;
    return new Time(h, m);
}

public int Minutes { get { return minutes; } set { minutes = value % 60; } }

class Program
{
    static void Main(string[] args)
    {
        Time t1 = new Time(9, 30);
        Time t2 = t1;
        t1.minutes = 100;
        Console.WriteLine("The time is: \nt1={0}  \nt2={1} ", t1, t2);
        Time t3 = t1 + 45;
    }
}
}

好的做法:hoursminutes 变量应该是 private 而不是 public,如果你提供 gettersetter那.

我不知道您的确切要求,但我认为下面的代码

public int Minutes { get { return minutes; } set { minutes = value % 60; } }

应该替换为以下内容:

public int Minutes { 
        get { return minutes; } 
        set {
            if (value > 60)
                hours = hours + (int)value / 60;
            minutes = value % 60; 
        } 
    }

希望这会有所帮助。