開発環境
- OS: Windows 10 Pro
- IDE(統合開発環境): Visual Studio Community 2017
初めてのC# 第2版 (Jesse Liberty (著)、Brian MacDonald (著)、日向 俊二 (翻訳)、オライリージャパン)の12章(演算子のオーバーロード)、12.6(練習問題)、練習12-2.を取り組んでみる。
コード
using System; using System.Collections.Generic; 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{0}: {1}", b, 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 static bool operator ==(Invoice lhs, Invoice rhs) { return lhs.vendor == rhs.vendor && lhs.amount == rhs.amount; } public static bool operator !=(Invoice lhs, Invoice rhs) { return !(lhs == rhs); } public override bool Equals(object obj) { if (obj is Invoice) { return this == (Invoice)obj; } return false; } public override string ToString() { return "Vendor: " + this.vendor + ", Amount: " + this.amount; } public override int GetHashCode() { var hashCode = -1567371628; hashCode = hashCode * -1521134295 + EqualityComparer<string>.Default.GetHashCode(vendor); hashCode = hashCode * -1521134295 + amount.GetHashCode(); return hashCode; } }
入出力結果(コマンドプロンプト)
Vendor: vendor1, Amount: 10 Vendor: vendor1, Amount: 10: True Vendor: vendor1, Amount: 20: False Vendor: vendor2, Amount: 30: False Vendor: vendor1, Amount: 20 Vendor: vendor1, Amount: 10: False Vendor: vendor1, Amount: 20: True Vendor: vendor2, Amount: 30: False Vendor: vendor2, Amount: 30 Vendor: vendor1, Amount: 10: False Vendor: vendor1, Amount: 20: False Vendor: vendor2, Amount: 30: True 続行するには何かキーを押してください . . .
0 コメント:
コメントを投稿