当前位置: 移动技术网 > IT编程>开发语言>c# > C#以对象为成员的例子

C#以对象为成员的例子

2019年11月12日  | 移动技术网IT编程  | 我要评论
using system;
using system.collections.generic;
using system.text;
namespace test
{
    class program
    {
        static void main(string[] args)
        {
            date birthday = new date(1999, 11, 11, new time(16, 33, 22));//传入的第四个参数是对象
            console.writeline("我出生于{0}年{1}月{2}日{3}", birthday.year, birthday.month, birthday.day, birthday.clock.to24());//调用第四个对象的方法
        }
    }
    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()//显示24小时制方法
        {
            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;
        }
    }
    class date
    {
        public int year;
        public int month;
        public int day;
        public time clock;//对象定义为成员
        public date(int yearvalue, int monthvalue, int dayvalue, time clockvalue)
        {
            year = yearvalue;
            month = monthvalue;
            day = dayvalue;
            clock = clockvalue;
        }
    }
}

 

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网