2012年7月24日火曜日

開発環境

『初めてのC# 第2版』(Jesse Liberty+Brian MacDonald著、日向俊二訳、オライリー・ジャパン、2006年、ISBN978-487311-294-7)の 第12章(演算子のオーバーロード)12.6(練習問題)、練習12-2を解いてみる。

練習12-2.

コード

using System;

namespace Sample
{
    class Invoice
    {
        private string vendor;
        private double amount;
        public Invoice(string vendor, double amount)
        {
            this.vendor = vendor;
            this.amount = amount;
        }
        public static Invoice operator +(
            Invoice lhs, Invoice rhs)
        {
            if (lhs.vendor == rhs.vendor)
            {
                return new Invoice(
                    lhs.vendor, lhs.amount +
                    rhs.amount);
            }
            else
            {
                return new Invoice("", 0);
            }
        }
        public override string ToString()
        {
            return "Vendor:" + vendor +
                ", Amount: " + amount;
        }
        public static bool operator ==(Invoice lhs, Invoice rhs)
        {
            if (lhs.vendor == rhs.vendor && lhs.amount == rhs.amount)
            {
                return true;
            }
            return false;
        }
        public static bool operator !=(Invoice lhs, Invoice rhs)
        {
            return !(lhs == rhs);
        }
        public override bool Equals(object obj)
        {
            if (!(obj is Invoice))
            {
                return false;
            }
            return this == (Invoice)obj;
        }
    }
    class Tester
    {
        public void Run()
        {
            Invoice a = new Invoice("yamato", 10);
            Invoice b = new Invoice("yamato", 20);
            Invoice c = new Invoice("sagawa", 10);
            Invoice d = new Invoice("sagawa", 20);
            Invoice e = new Invoice("yamato", 10);
            Invoice[] invoices = { b, c, d, e };
            foreach (Invoice invoice in invoices)
            {
                Console.WriteLine("{0}, {1}, {2}",
                    a == invoice, a != invoice, a.Equals(invoice));
            }
            int n = 10;
            Console.WriteLine(n.Equals(a));
        }
        static void Main()
        {
            Tester t = new Tester();
            t.Run();
        }
    }
}

入出力結果(Console Window)

False, True, False
False, True, False
False, True, False
True, False, True
False
続行するには何かキーを押してください . . .

0 コメント:

コメントを投稿