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

C#以对象为成员的例子

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

C#以对象为成员的例子