效果
代码
Program.cs
空的,Time类放在了Form1.cs中
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace 第五章_显示时间
{
}
Form1.cs
50行:在class类中增加了 AddSecond()
方法,在button1_Click事件中调用
注意29~31行,为了使用AddSecond()
方法,将时、分、秒的属性改成了可读可写
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 第五章_显示时间
{
static class Program
{
/// <summary>
/// 应用程序的主入口点。
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
public class Time
{
//只读属性
public int Hour { get; set; }
public int Min { get; set; }
public int Sec { get; set; }
//构造函数
public Time()
{
Hour = System.DateTime.Now.Hour;
Min = System.DateTime.Now.Minute;
Sec = System.DateTime.Now.Second;
}
//重载
public Time(int h, int m, int s)
{
Hour = h;
Min = m;
Sec = s;
}
//点击加一AddSecond
public void AddSecond()
{
//计算进位
Sec += 1;
if (Sec >= 60)
{
Sec = 0;
Min += 1;
if (Min >= 60)
{
Min = 0;
Hour += 1;
if (Hour >= 24)
{
Hour = Min = Sec = 0;
}
}
}
}
}
public partial class Form1 : Form
{
Time time = new Time();
public Form1()
{
InitializeComponent();
//输出当前时间
textBox1.Text = time.Hour.ToString();
textBox2.Text = time.Min.ToString();
textBox3.Text = time.Sec.ToString();
}
private void button1_Click(object sender, EventArgs e)
{
//加一计算
time.AddSecond();
//输出
textBox1.Text = time.Hour.ToString();
textBox2.Text = time.Min.ToString();
textBox3.Text = time.Sec.ToString();
}
}
}