日期:2009-10-18  浏览次数:20494 次

大家好!好久没有上来了!小生在此向各方豪杰问好!
今天温习了一下C#,解决了老大一个难题,以前总是搞不懂重载运算符,也不知道它有什么用处,

今天总算把它给用上了,真有种在深山老林里用上电得感觉,呵呵!我用它做了一个计时器,下面
我就把代码帖出来供大家玩乐一下也好!先把步骤说一下:
1.用.net建立一个Windows应用程序
2.在项目下添加一个类命名为“Time“
3.编写“Time“类得实现代码
4.在窗体中放两个Label控件和一个时钟(Timer)控件
5.编写窗体得Load事件和(Timer)控件的Tick事件

以下是“Time“类得实现代码:
public class Time
{
private int hours; //小时
private int minutes; //分钟
private int seconds; //秒钟

public Time()
{
this.hours = 0;
this.minutes = 0;
this.seconds = 0;
}

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

public void SetHours(int hours)
{
this.hours = hours;
}

public void SetMinutes(int minutes)
{
this.minutes = minutes;
}

public void SetSeconds(int seconds)
{
this.seconds = seconds;
}

public int GetHours()
{
return this.hours;
}

public int GetMinutes()
{
return this.minutes;
}

public int GetSeconds()
{
return this.seconds;
}

public static Time operator ++(Time time)
{
time.seconds++;
if (time.seconds >= 60)
{
time.minutes++;
time.seconds = 0;
if (time.minutes >= 60)
{
time.hours++;
time.minutes = 0;
time.seconds = 0;
if (time.hours >= 24)
{
time.hours = 0;
time.minutes = 0;
time.seconds = 0;
}
}
}
return new Time(time.hours,time.minutes,time.seconds);
}
}

以下是Load事件和Timer控件的Tick事件处理程序:
private void Form1_Load(object sender, System.EventArgs e)
{
DateTime dtime = DateTime.Now;
int hour = dtime.Hour;
int minute = dtime.Minute;
int second = dtime.Second;
time = new Time(hour,minute,second);
this.label1.Text = "当前时间是:" + hour + ":" + minute + ":" + second;
this.timer1.Start();
}
private void timer1_Tick(object sender, System.EventArgs e)
{
time++;
this.label2.Text = "时间在流逝:" + time.GetHours() + ":" + time.GetMinutes() + ":" + time.GetSeconds();
}