芭芭拉 默瑞:C#编程问题

来源:百度文库 编辑:杭州交通信息网 时间:2024/04/30 16:21:08
下面我的程序有错:
using System;

public struct MyDate
{
public int year;
public int month;
public int date;

public MyDate(int year, int month, int date)
{
this.year = year;
this.month = month;
this.date = date;
}

public override string ToString()
{
return string.Format("{0}/{1}/{2}", year,month,date);
}

}

namespace ConsoleApplication7
{
public class Exercise1
{

public MyDate parseDate(String aDate)
{
bool isValid = true;
int year = -1;
int month = -1;
int date = -1;
try
{
year = int.Parse(aDate.Substring(0, 4));
month = int.Parse(aDate.Substring(5, 7));
date = int.Parse(aDate.Substring(8, 10));
/* if (aDate.charAt(4) != '/' || aDate.charAt(7) != '/')
throw new ArgumentException();*/
}
catch
{
isValid = false;
}
if (isValid)
isValid = isValidDate(year, month, date);
MyDate myDate = null;
if (isValid)
myDate = new MyDate(year, month, date);
return myDate;
}

public bool isValidDate(int year, int month, int date)
{
bool isValid = true;
if (year < 1
|| month < 1 || month > 12
|| date < 1 || date > daysOfMonth[month])
{
isValid = false;
}
else if (month == 2 && date == 29 && !isLeap(year))
isValid = false;
return isValid;
}

public bool isLeap(int year)
{
return (year % 400 == 0 || (year % 100 != 0 && year % 4 == 0));
}

public int daysBeforeYear(int year)
{
int years = year - 1;
int sum = years * 365;
sum += years / 4;
sum -= years / 100;
sum += years / 400;
return sum;
}

public int toDays(MyDate aDate)
{
int days = aDate.date;
days += daysBeforeMonth[aDate.month];
days += daysBeforeYear(aDate.year);
if (aDate.month > 2 && isLeap(aDate.year))
days++;
return days;
}
public int GetDiffDays(String date1, String date2)
{
MyDate my1 = parseDate(date1);
if (my1 == null)
throw new ArgumentException("Illegal Date format: " + date1);
MyDate my2 = parseDate(date2);
if (my2 == null)
throw new ArgumentException("Illegal Date format: " + date2);
return toDays(my1) - toDays(my2);
}
public static void main(String[] args)
{
Exercise1 ex1 = new Exercise1();
try
{
Console.WriteLine(ex1.GetDiffDays("2003/07/03", "2004/07/03"));
Console.WriteLine(ex1.GetDiffDays("2005/07/03", "2005/07/03"));
Console.WriteLine(ex1.GetDiffDays("2005/07/03", "2004/07/03"));
Console.WriteLine(ex1.GetDiffDays("2000/02/29", "1900/02/29"));
}
catch (ArgumentException e)
{
Console.WriteLine("{0} Exception caught.", e);
}
}

}
}

说我的 Cannot convert null to 'MyDate' because it is a value type
为什么阿?
大家帮帮我

MyDate myDate = null;
改为:
MyDate myDate = new MyDate();