2013年9月15日 星期日

運算子多載

當搭配自己的資料型別使用時,可以重新定義更有意義的運算子。在下列範例中會建立結構 (Struct),以便將一週中的一天儲存在列舉型別 (Enumeration) 所定義的變數型別中。
using System;

// Define an DayOfWeek data type
enum DayOfWeek { Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday };

// Define a struct to store the methods and operators
struct Day 
{
    private DayOfWeek day;

    // The constructor for the struct
    public Day(DayOfWeek initialDay)
    {
        day = initialDay;
    }

    // The overloaded + operator
    public static Day operator +(Day lhs, int rhs)
    {
        int intDay = (int)lhs.day;
        return new Day((DayOfWeek)((intDay + rhs) % 7));
    }

    // An overloaded ToString method
    public override string ToString()
    {
        return day.ToString();
    }
}

public class Program
{
    static void Main()
    {
        // Create a new Days object called "today"
        Day today = new Day(DayOfWeek.Sunday);
        Console.WriteLine(today.ToString());

        today = today + 1;
        Console.WriteLine(today.ToString());

        today = today + 14;
        Console.WriteLine(today.ToString());
    }
}

沒有留言:

張貼留言