using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace structType
{
class Program
{
static void Main(string[] args)
{
Date defaultDate = new Date(); // 使用默認構造器
Console.WriteLine("使用結構的默認構造器輸出:{0}", defaultDate);
// 實際上,輸出時調用了重寫的 ToString 方法
Console.WriteLine("使用結構的默認構造器輸出:{0}", defaultDate.ToString());
// 和上句效果一樣,上句省略了 ToString 方法
Date weddingAnniversary = new Date(2010, Month.July, 4);
Console.WriteLine("使用自定義的構造器輸出:{0}", weddingAnniversary);
// 調用了重寫的 ToString 方法
}
}
struct Date
{
private int year; // 0 無效
private Month month; // 0 爲枚舉類型中的 January
private int day; // 0 無效
public Date(int ccyy, Month mm, int dd)
{
this.year = ccyy - 1900;
this.month = mm;
this.day = dd - 1;
}
public override string ToString() // 重寫 ToString 方法
{
string data = string.Format("{0} {1} {2}", this.month,
this.day + 1,
this.year + 1900);
return data;
}
}
enum Month // enum 類型
{
January, Feburary, March,
April, May, June,
July, August, September,
October, November, December
}
}
運行後結果如下所示: