欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2023-11-18 13:17:34
using System; using System.Collections.Generic; using System.Text; namespace test { class Program { static void Main(string[] args) { Time test1 = new ......
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;
        }
    }
}

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