将Int转换为String以显示时间
本文关键字:显示 时间 String Int 转换 | 更新日期: 2023-09-27 18:11:37
帮我写代码。我试图使用ToString()
方法将int
转换为time
格式。当我运行它时,我得到09:100。我可以做什么,特别是使用getters
和setters
?
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;
}
}
}
在main method change t1.minutes = 100;
to 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;
}
}
}
好的做法:hours
和minutes
变量应该是private
而不是public
,如果你提供getter
和setter
。
我不知道你的确切要求,但我认为下面的代码
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;
}
}