本文主要是介绍自定义一个时间类。该类包含小时、分、秒字段与属性,具有将秒增加1秒的方法。,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
要求定义一个Time类,包括以下内容。
3个私有字段,表示时、分、秒。
两个构造函数,一个通过传入的参数对时间初始化,另一个获取系统当前的时间。
3个只读属性对时、分、秒的读取。
一个方法用于对秒增加1秒(注意60进位的问题)。
图形界面
从左到右name:txtHour,txtMin,txtSec
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;namespace WindowsFormsApp6
{public partial class Form1 : Form{public Form1(){InitializeComponent();}class Time //定义时间类{private int hour;private int minute;private int second;public Time() //构造函数,用于获取当前的时间{hour = System.DateTime.Now.Hour; //获取系统当前的小时minute = System.DateTime.Now.Minute; //获取系统当前的分钟second = System.DateTime.Now.Second; //获取系统当前的秒}public Time(int h, int m, int s) //构造函数,用于通过传入的参数对时间初始化{hour = h; minute = m; second = s;}public int Hour //只读属性,对时读取{get{return hour;}}public int Minute //只读属性,对分读取{get{return minute;}}public int Second //只读属性,对秒读取{get{return second;}}public void AddSecond() //方法AddSecond(),用于对秒增加1秒{second++;if (second >= 60){second = second % 60; //逢60秒进位到minuteminute++;}if (minute >= 60){minute = minute % 60; //逢60分进位到hourhour++;}if (hour >= 24){hour = hour % 24; //逢24小时归到0点}}}Time T = new Time();private void button1_Click(object sender, EventArgs e){T.AddSecond(); //调用方法成员AddSecond();txtHour.Text = Convert.ToString(T.Hour); //调用对象的属性成员并转化为字符串在控件中显示txtMin.Text = Convert.ToString(T.Minute); //调用对象的属性成员并转化为字符串在控件中显示txtSec.Text = Convert.ToString(T.Second); //调用对象的属性成员并转化为字符串在控件中显示}}
}
这篇关于自定义一个时间类。该类包含小时、分、秒字段与属性,具有将秒增加1秒的方法。的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!