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

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值