C#中操作符的重载(Time类)
今天在写一个计时器的Time类,其中想写一些比较简单的方法,所以用到了C#中的操作符的重载,以前会写的居然只有C++的操作符重载,原来自己没遇到过,居然却不会写C# 的操作符重载(虽然C# 的操作符重载要简单得多,但是真正写出来了,才是硬道理啊!)
下面附上我写的Time类,里面有个操作符“++”的重载,“++”的重载会在后面的应用中简单很多呢。。
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; if (time.hours >= 24) { time.hours = 0; time.seconds = 0; time.minutes = 0; } } } return new Time(time.hours, time.minutes, time.seconds); } }
Time类还有很多的功能没写,先上着用,有机会完善,而且这个类也太简单了。。