開発環境
- OS: macOS High Sierra - Apple
- IDE(統合開発環境): Visual Studio for Mac
- プログラミング言語: C#
初めてのC# 第2版 (Jesse Liberty (著)、Brian MacDonald (著)、日向 俊二 (翻訳)、オライリージャパン)の12章(演算子のオーバーロード)、12.6(練習問題)、練習12-1.を取り組んでみる。
コード
using System;
namespace Sample12_1
{
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 string.Format("Vendor: {0}, Amount: {1}", vendor, amount);
}
}
class Program
{
static void Main(string[] args)
{
Invoice i = new Invoice("vendor1", 10);
Invoice i1 = new Invoice("vendor1", 20);
Invoice i2 = new Invoice("vendor2", 30);
Invoice[] a = { i1, i2 };
Console.WriteLine("{0}\n", i);
foreach (var item in a)
{
Console.WriteLine("\t{0}\n\t{1}\n", item, i + item);
}
}
}
}
入出力結果(Terminal)
Vendor: vendor1, Amount: 10 Vendor: vendor1, Amount: 20 Vendor: vendor1, Amount: 30 Vendor: vendor2, Amount: 30 Vendor: , Amount: 0 Press any key to continue...
0 コメント:
コメントを投稿