一个不错的代码复用
时间:2010-10-13 来源:iejwduan
这是一个计算一年中的日期具体是一年的哪一天的小Date类,例如2010年10月1号是2010年的哪一天?感觉这个类中有些不错的代码亮点和思想。读一段代码,有时候真的是如读一个精彩的短篇小说一样的令人回味。
using System;
class Date
{
int year;
int month;
int day;
static int[] MonthDays = new int[] { 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334 };
public Date()
{
Year = 1600;
Month = 1;
Day = 1;
}
public Date(int year, int month, int day)
{
if ((month == 2 && IsLeapYear(year) && day > 29) ||
(month == 2 && !IsLeapYear(year) && day > 28) ||
((month == 4 || month == 6 || month == 9 || month == 11) && day > 30))
{
throw new ArgumentOutOfRangeException("Day");
}
else
{
Year = year;
Month = month;
Day = day;
}
}
public int Year
{
set
{
if (value < 1600)
throw new ArgumentOutOfRangeException("Year");
else
year = value;
}
get
{
return year;
}
}
public int Month
{
set
{
if (value < 1 || value > 12)
throw new ArgumentOutOfRangeException("Month");
else
month = value;
}
get
{
return month;
}
}
public int Day
{
set
{
if (value < 1 || value > 31)
throw new ArgumentOutOfRangeException("Day");
else
day = value;
}
get
{
return day;
}
}
public static bool IsLeapYear(int year)
{
return (year % 4 == 0) && ((year % 100 != 0)) || (year % 400 == 0);
}
public int DayOfYear
{
get
{
return MonthDays[month - 1] + day + (month > 2 && IsLeapYear(year) ? 1 : 0);
}
}
}
下面是对这个类的一个应用,用于统计两个年份之间的具体相差天数
using System;
class CsDateInheritance
{
public static void Main()
{
DatePlus birth = new DatePlus(1986, 11, 15);
DatePlus today = new DatePlus(2010, 10, 12);
Console.WriteLine("Birthday = {0}", birth);
Console.WriteLine("Today = " + today);
Console.WriteLine("Days since birthday = {0}", today - birth);
}
}
class DatePlus : Date
{
public DatePlus() { }
public DatePlus(int year, int month, int day) : base(year, month, day) { }
public int DaysSince1600
{
get
{
return 365 * (Year - 1600) + (Year - 1597) / 4 - (Year - 1601) / 100 + (Year - 1601) / 400 + DayOfYear;
}
}
public override string ToString()
{
string[] str = { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Ju", "Aug", "Sep", "Oct", "Nov", "Dec" };
return String.Format("{0} {1} {2}", Day, str[Month - 1], Year);
}
public static int operator -(DatePlus date1, DatePlus date2)
{
return date1.DaysSince1600 - date2.DaysSince1600;
}
}