C#以對象爲成員的例子

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;
        }
    }
}

相關文章
相關標籤/搜索