帮我解决我的代码问题。我正在尝试使用int
方法将time
格式转换为ToString()
格式。当我跑它时,我得到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;
}
}
}
答案 0 :(得分:0)
在主要方法中,将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;
}
}
}
良好做法: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;
}
}
希望这会有所帮助。