C# 实验四 修改版 获取系统时间、点击加一秒功能

效果

在这里插入图片描述

代码

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();
        }
    }
}

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值