C#---定义一个时间类,该类包括小时、分、秒字段和相应的属性,具有将秒增加1的方法。要求定义一个Time类

定义一个时间类,该类包括小时、分、秒字段和相应的属性,具有将秒增加1的方法。要求定义一个Time类,包括: (1)3个私有字段表示时分秒
(2)两个构造函数,一个可以通过传入的参数对时间初始化,一个获取当前系统时间(把对象中的时分秒初始化为当前系统时间的时分秒)
(3)3个只读属性对时、分、秒进行读取 (4)一个方法用于对秒增1的操作(注意秒和分的进位)

获取时分秒的函数:
DateTime.Now.Hour.ToString();//获取当前时间
DateTime.Now.Minute.ToString();//获取当前分钟
DateTime.Now.Second.ToString();//获取当前秒

类:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace test
{
    class Time
    {
        private int hour;
        private int min;
        private int second;

        public Time(int hour, int min, int second)
        {
            this.hour = hour;
            this.min = min;
            this.second = second;
        }
        public Time()
        {
            this.hour = int.Parse(DateTime.Now.Hour.ToString());
            this.min = int.Parse(DateTime.Now.Minute.ToString());
            this.second = int.Parse(DateTime.Now.Second.ToString());
        }
        public int Hour
        {
            get
            {
                return hour;
            }
        }
        public int Min
        {
            get
            {
                return min;
            }
        }
        public int Second
        {
            get
            {
                return second;
            }
 
        }
        public void add()
        {
            second++;
            if (second == 60) {     //如果满60s了就进一位
                second = 0;
                min += 1;
            }
            if (min == 60) {
                min = 0;
                hour =hour + 1;
            }
            if(hour == 24)
            {

            }

        }

        public void show()
        {
            Console.WriteLine("{0}:{1}:{2}", Hour, Min, Second);
        }
    }
}

主函数:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace test
{
    class Program
    {
       
        static void Main(string[] args)
        {
            Time t1 = new Time(12,59,59);
            Time t2 = new Time();
            t1.show();
            t1.add();
            Console.WriteLine("增加1s后的时间:");
            t1.show();
            Console.WriteLine("系统当前时间:");
            t2.show();
            Console.ReadLine();
        }
    }
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值