本帖最后由 wwwconsumer 于 2015-5-30 10:45 编辑
为了巩固对类的理解,我们来设计一个关于时间的类,该类的成员如下表:访问权限 | 类型 | 成员 | 说明 | private | int | hour | 私有变量 | private | int | minute | ]私有变量 | private | int | second | 私有变量] | public | int | Hour | 变量hour的属性 | public | int | Minute | 变量minute的属性 | public | int | Second | 变量second的属性 | public | void | SetTime() | 私有函数,用来设置时间 | private | void | Time() | 构造函数,无参数 | public | void | Time(int hourValue) | 构造函数,一个参数 | public | void | Time(int hourValue,int minuteValue,secondValue) | 构造函数,三个参数 | public | void | ToString24() | 用24小时制格式输出时间 | public | void | ToString12() | 用12小时制格式输出时间 |
我们先编写一个Time类:
[C#] 纯文本查看 复制代码 using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Time
{
class Time
{
//私有成员
private int hour;
private int minute;
private int second;
private void SetTime(int h,int m,int s)
{
Hour =h;
Minute = m;
Second = s;
}
//构造函数,无参数
public Time()
{
SetTime(0, 0, 0);
}
//构造函数,一个参数
public Time(int hourValue)
{
SetTime(hourValue, 0, 0);
}
//构造函数,三个参数
public Time(int hourValue, int minuteValue, int secondValue)
{
SetTime(hourValue ,minuteValue,secondValue);
}
//属性
public int Hour
{
get
{
return hour;
}
set
{
hour =((value >=0&&value<24?value :0));
}
}
//属性Minute
public int Minute
{
get
{
return minute;
}
set
{
minute =((value >=0&&value<60)?value:0);
}
}
//属性Second
public int Second
{
get
{
return second;
}
set
{
second =((value >=0&&value<60)?value:0);
}
}
//函数,返回24小时
public string ToString24()
{
string output = Hour + ":" + Minute + ":" + Second;
return output;
}
//函数,返回12小时制时间
public string ToString12()
{
int hourTemp =((Hour ==12)||(Hour ==0))?12:(Hour%12);
string AMPM=(Hour <12?"AM":"PM");
string output = hourTemp + ":" + Minute + ":" + Second + AMPM;
return output;
}
}
}
然后,在program.cs中运行下列代码:
[C#] 纯文本查看 复制代码 using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Time
{
class Program
{
static void Main(string[] args)
{
Time time1 = new Time();
Time time2 = new Time(22);
Time time3 = new Time(22,36,30);
Console.WriteLine("time1:");
Console.WriteLine("24小时制时间:"+ time1.ToString24());
Console.WriteLine("12小时制时间" + time1.ToString12() + "\n");
Console.WriteLine("time2:");
Console.WriteLine("24小时制时间:" + time2.ToString24());
Console.WriteLine("12小时制时间" + time2.ToString12() + "\n");
Console.WriteLine("time3:");
Console.WriteLine("24小时制时间:" + time3.ToString24());
Console.WriteLine("12小时制时间" + time3.ToString12() + "\n");
Date birthday = new Date(1981, 12, 3, new Time(16,30,0));
Console.Write("我出生于{0}年{1}月{2}日{3}。", birthday.year, birthday.month, birthday.day, birthday.clock.ToString24());
}
}
}
运行结果如下:
|