C#语言学习--基础部分(十四)枚举类型和结构体(续)

结构体与类的区别:

1.不能给结构体定义默认的构造方法

2.在结构体中非默认的构造方法中你必须对结构体中所有的字段进行初始化,否则将报错

3.在类中声明字段的同时,你可以初始化字段的值。但是在结构体中,不可以.

ConsoleDemo:

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace StructsEnums
{
    struct Date {
        private int year;
        private Month month;
        private int day;
        public Date(int ccyy,Month mm,int dd) {
            this.year = ccyy - 1900;
            this.month = mm;
            this.day = dd -1;
        }
        
        public override string ToString()
        {
            string data = String.Format("{0} {1} {2}",this.month,this.day+1,this.year+1900);
            return data;
        }
        public void AdvanceMonth()
        {
            this.month++;
            if (this.month == Month.December + 1)
            {
                this.month = Month.January;
                this.year++;
            }
        }
    }
    enum Month {
        January,February,March,April,May,June,July,August,Septempber,October,November,December
    }
    class Program
    {
        static void Main(string[] args)
        {
            doWork();
        }
        static void doWork()
        {
            Month first = Month.January;
            first = Month.December;
            Console.WriteLine(first);
            first++;
            Console.WriteLine(first);
            Date defaultDate = new Date();
            Console.WriteLine(defaultDate);
            Date currentDate = new Date(2012, Month.August, 25);
            Console.WriteLine(currentDate);
            Date secondDate = currentDate;
            Console.WriteLine(secondDate);
            currentDate.AdvanceMonth();
            Console.WriteLine(currentDate);
            Console.WriteLine(secondDate);
            Date futureDate = new Date(2012, Month.December, 25);
            futureDate.AdvanceMonth();
            Console.WriteLine(futureDate);
        }
    }
}

 

posted on 2012-08-26 01:00  松波  阅读(232)  评论(0编辑  收藏  举报

导航