次の例は、書籍Programming in the Key of C#からのものです。
プログラムの最初の繰り返しは典型的な C の方法であり、次の生まれ変わりはよりオブジェクト指向です。このプログラムは、特定のイベントが発生した日付を計算する簡単な例です (12 月 31 日は 365 日、閏年の場合は 366 日です)。
using System;
class StructureAndMethodsTwo
{
static void Main()
{
Date dateMoonWalk = new Date();
dateMoonWalk.iYear = 1969;
dateMoonWalk.iMonth = 7;
dateMoonWalk.iDay = 20;
Console.WriteLine("Moon walk: {0}/{1}/{2} Day of Year: {3}",
dateMoonWalk.iMonth, dateMoonWalk.iDay, dateMoonWalk.iYear,
Date.DayOfYear(dateMoonWalk));
}
}
struct Date
{
public int iYear;
public int iMonth;
public int iDay;
public static bool IsLeapYear(int iYear)
{
return iYear % 4 == 0 && (iYear % 100 != 0 || iYear % 400 == 0);
}
static int[] aiCumulativeDays = { 0, 31, 59, 90, 120, 151,
181, 212, 243, 273, 304, 334 };
public static int DayOfYear(Date dateParam)
{
return aiCumulativeDays[dateParam.iMonth - 1] + dateParam.iDay +
(dateParam.iMonth > 2 && IsLeapYear(dateParam.iYear) ? 1 : 0);
}
}
DayOfYear
プログラムの次のバージョンは、次のようになるメソッドを除いて同じです。
public int DayOfYear()
{
return aiCumulativeDays[iMonth -1] + iDay+ (iMonth > 2 && IsLeapYear(iYear) ? 1:0);
}
最初のバージョンよりも OOP フレンドリーになっている 2 番目のバージョンで正確に何が起こっているのでしょうか? 最初の反復でDate
メソッドによってタイプのオブジェクトが作成されていますか? DayOfYear
メソッドのインスタンス バージョンが構造体のフィールドに直接アクセスできることは知っていますが、その明確な利点については認識していません。