using System;
namespace MyDate
{
class Program
{
static void Main(string[] args)
{
MyDate oneDate = new MyDate();
MyDate twoDate = new MyDate(3, 22, 2021);
twoDate.Day = 21;
twoDate.DisplayDate();
}
}
class MyDate
{
private int day, month, year;
public int Day
{
get { return day; }
set
{
if (Check(value, month, year)) day = value;
Console.WriteLine("时间设置为:{0}", this);//this的用法?
}
}
public int Month
{
get { return month; }
set
{
if (Check(day, value, year)) month = value;
Console.WriteLine("时间设置为:{0}", this);
}
}
public int Year
{
get { return year; }
set
{
if (Check(day, month, value)) year = value;
Console.WriteLine("时间设置为:{0}", this);
}
}
static private bool Check(int day,int month,int year)
{
if (Vaildity(day, month, year)) return true;
Console.WriteLine("日期{0}/{1}/{2}不合法", day, month, year);
return false;
}
static int[] day_12 = { 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
static private bool Vaildity(int day, int month, int year)//检查日期的合法性
{
if (day < 0 || day > 31 || month < 0 || month > 12 || year < 0) return false;
if (day > day_12[month - 1]) return false;
if(month==2&&day==29)
{
if (year % 4 == 0) return true;
else return false;
}return true;
}
public MyDate() : this(1, 1, 1990) { }
public MyDate(int a, int b, int c)
{
if(Vaildity(a,b,c))
{
day = a;month = b;year = c;
}
else
{
Console.WriteLine("设置的日期不合法");
a = 1; b = 1; c = 1990;
Console.WriteLine("默认日期为:{0}", this);
}
}
public override string ToString() { return string.Format("{0}/{1}/{2}", day, month, year); }
public void DisplayDate() { Console.WriteLine("\n" + this + "\n"); }
}
}