開発環境
- Microsoft Windows 7 Home Premium (OS)
- Microsoft Visual C# 2010 Express Edition (IDE)
- 言語: C#
『初めてのC# 第2版』(Jesse Liberty+Brian MacDonald著、日向俊二訳、オライリー・ジャパン、2006年、ISBN978-487311-294-7)の 第12章(演算子のオーバーロード)12.6(練習問題)練習12-2を解いてみる。
その他参考書籍
練習12-2.
コード
using System;
class Invoice
{
private string vendor;
private double amount;
public Invoice(string vendor, double amount)
{
this.vendor = vendor;
this.amount = amount;
}
public string Vendor
{
get { return vendor; }
set { vendor = value; }
}
public double Amount
{
get { return amount; }
set { amount = value; }
}
public static Invoice operator +(Invoice lhs, Invoice rhs)
{
if (lhs.vendor == rhs.vendor)
{
return new Invoice(lhs.vendor, lhs.amount + rhs.amount);
}
return null;
}
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;
}
public override string ToString()
{
return "Vendor: " + this.vendor + ", Amount: " + this.amount;
}
public override int GetHashCode()
{
return base.GetHashCode();
}
}
class Tester
{
public void Run()
{
Invoice yamato = new Invoice("yamato", 5);
Invoice yamato1 = new Invoice("yamato", 5);
Invoice yamato2 = new Invoice("yamato", 10);
Invoice sagawa1 = new Invoice("sagawa", 5);
Invoice sagawa2 = new Invoice("sagawa", 10);
Invoice[] invoices = { yamato1, yamato2, sagawa1, sagawa2 };
foreach (Invoice item in invoices)
{
Console.WriteLine("({0}) == ({1}): {2}", yamato, item, yamato == item);
Console.WriteLine("({0}).Equals({1}): {2}", yamato, item, yamato.Equals(item));
}
Console.WriteLine("({0}).Equals({1}): {2}", yamato, 10, yamato.Equals(10));
}
static void Main()
{
Tester t = new Tester();
t.Run();
}
}
入出力結果(Console Window)
(Vendor: yamato, Amount: 5) == (Vendor: yamato, Amount: 5): True (Vendor: yamato, Amount: 5).Equals(Vendor: yamato, Amount: 5): True (Vendor: yamato, Amount: 5) == (Vendor: yamato, Amount: 10): False (Vendor: yamato, Amount: 5).Equals(Vendor: yamato, Amount: 10): False (Vendor: yamato, Amount: 5) == (Vendor: sagawa, Amount: 5): False (Vendor: yamato, Amount: 5).Equals(Vendor: sagawa, Amount: 5): False (Vendor: yamato, Amount: 5) == (Vendor: sagawa, Amount: 10): False (Vendor: yamato, Amount: 5).Equals(Vendor: sagawa, Amount: 10): False (Vendor: yamato, Amount: 5).Equals(10): False 続行するには何かキーを押してください . . .
0 コメント:
コメントを投稿