2018年5月5日土曜日

開発環境

初めてのC# 第2版 (Jesse Liberty (著)、Brian MacDonald (著)日向 俊二 (翻訳)、オライリージャパン)の12章(演算子のオーバーロード)、12.6(練習問題)、練習12-1.を取り組んでみる。

コード

using System;

class Program
{
    static void Main(string[] args)
    {
        Invoice i1 = new Invoice("vendor1", 10);
        Invoice i2 = new Invoice("vendor1", 20);
        Invoice i3 = new Invoice("vendor2", 30);

        Invoice[] invoices = { i1, i2, i3 };
        foreach (Invoice a in invoices)
        {
            Console.WriteLine(a);
            foreach (Invoice b in invoices)
            {
                Console.WriteLine("\t" + b);
                Console.WriteLine("\t\t" + (a + b));
            }
        }
    }

}
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);
        }
        return new Invoice("", 0);
    }

    public override string ToString()
    {
        return "Vendor: " + this.vendor + ", Amount: " + this.amount;
    }
}

入出力結果(コマンドプロンプト)

Vendor: vendor1, Amount: 10
        Vendor: vendor1, Amount: 10
                Vendor: vendor1, Amount: 20
        Vendor: vendor1, Amount: 20
                Vendor: vendor1, Amount: 30
        Vendor: vendor2, Amount: 30
                Vendor: , Amount: 0
Vendor: vendor1, Amount: 20
        Vendor: vendor1, Amount: 10
                Vendor: vendor1, Amount: 30
        Vendor: vendor1, Amount: 20
                Vendor: vendor1, Amount: 40
        Vendor: vendor2, Amount: 30
                Vendor: , Amount: 0
Vendor: vendor2, Amount: 30
        Vendor: vendor1, Amount: 10
                Vendor: , Amount: 0
        Vendor: vendor1, Amount: 20
                Vendor: , Amount: 0
        Vendor: vendor2, Amount: 30
                Vendor: vendor2, Amount: 60
続行するには何かキーを押してください . . .

0 コメント:

コメントを投稿

Comments on Google+: