欢迎来到萧静默的博客

书山有路勤为径,学海无涯苦作舟。

C#构造函数、属性的应用

using System;
using System.Collections.Generic;
using System.Text;
namespace test
{
    class Program
    {
        static void Main(string[] args)
        {
            Time test1 = new Time();
            Time test2 = new Time(11);
            Time test3 = new Time(11, 23, 12);
            Console.WriteLine("test1:");
            Console.WriteLine("24小时制:" + test1.To24());
            Console.WriteLine("12小时制:" + test1.To12());
            Console.WriteLine("test2:");
            Console.WriteLine("24小时制:" + test2.To24());
            Console.WriteLine("12小时制:" + test2.To12());
            Console.WriteLine("test3:");
            Console.WriteLine("24小时制:" + test3.To24());
            Console.WriteLine("12小时制:" + test3.To12());
        }
    }
    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//属性赋值
        {
            set { hour = (value >= 0 && value <= 24 ? value : 0); }
            get { return hour; }
        }
        public int Minute//属性赋值
        {
            set { minute = (value >= 0 && value <= 60 ? value : 0); }
            get { return minute; }
        }
        public int Second//属性赋值
        {
            set { second = (value >= 0 && value <= 60 ? value : 0); }
            get { return second; }
        }
        public string To24()//显示24小时制方法
        {
            string output = Hour + ":" + Minute + ":" + Second;
            return output;
        }
        public string To12()//显示12小时制方法
        {
            string output;
            if (Hour >= 12)
            {
                output = Hour % 12 + ":" + Minute + ":" + Second + "PM";
            }
            else
            {
                output = Hour % 12 + ":" + Minute + ":" + Second + "AM";
            }
            /*下面也是可以的
            int HOURTEMP = (Hour == 0 || Hour == 12) ? 00 : (Hour % 12);
            string PMAM = (Hour < 12) ? "AM" : "PM";
            string output1 = HOURTEMP + ":" + Minute + ":" + Second + PMAM;*/
            return output;
        }
    }
}

 

posted @ 2019-11-12 14:32  萧静默  阅读(836)  评论(0编辑  收藏  举报