【发布时间】:2015-09-25 20:59:46
【问题描述】:
帮我写代码。我正在尝试使用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;
}
}
}
【问题讨论】:
-
int代表什么? -
你的问题没有多大意义。尝试将其改写为对问题的完整和清晰的解释。你说你正在运行一些代码。我们要猜那是什么吗?更一般地说,如果您想输出时间格式,那么您将使用一个实际代表时间的对象,这意味着
TimeSpan或DateTime。也许将您的int转换为其中合适的一个,然后再调用ToString是合乎逻辑的。 -
请原谅。我不知道如何最好地问这个问题。无论如何,我将我的代码复制到了问题上。