#region Using directives
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Windows.Forms;
#endregion
namespace Indexers
{
partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void findPhone_Click(object sender, System.EventArgs e)
{
// to do
string text = name.Text;
if (text != "")
{
phoneNumber.Text = phoneBook[new Name(text)].Text;
}
}
private void findName_Click(object sender, System.EventArgs e)
{
// to do
string text = phoneNumber.Text;
if (text != "")
{
name.Text = phoneBook[new PhoneNumber(text)].Text;
}
}
private void add_Click(object sender, System.EventArgs e)
{
if (name.Text != "" && phoneNumber.Text != "")
{
phoneBook.Add(new Name(name.Text),
new PhoneNumber(phoneNumber.Text));
name.Text = "";
phoneNumber.Text = "";
}
}
private PhoneBook phoneBook = new PhoneBook();
}
}
、、、、、、、、、、、、、、、、、、、、、、、
namespace Indexers
{
struct Name
{
public Name(string text)
{
this.name = text;
}
public string Text//只读
{
get { return this.name; }
}
public override int GetHashCode()//比较
{
return this.name.GetHashCode();
}
public override bool Equals(object other)//比较
{
return (other is Name) && Equals((Name)other);
}
public bool Equals(Name other)// 比较
{
return this.name == other.name;
}
private string name;
}
}
namespace Indexers
{
struct PhoneNumber
{
public PhoneNumber(string text)
{
this.number = text;
}
public string Text
{
get { return this.number; }
}
public override int GetHashCode()
{
return this.number.GetHashCode();
}
public override bool Equals(object other)
{
return (other is PhoneNumber) && Equals((PhoneNumber)other);
}
public bool Equals(PhoneNumber other)
{
return this.number == other.number;
}
private string number;
}
}
namespace Indexers
{
using System;
sealed class PhoneBook
{
public PhoneBook()
{
int initialSize = 0;
this.used = 0;
this.names = new Name[initialSize];
this.phoneNumbers = new PhoneNumber[initialSize];
}
public void Add(Name name, PhoneNumber number)
{
enlargeIfFull();
this.names[used] = name;
this.phoneNumbers[used] = number;
this.used++;
}
public Name this[PhoneNumber number]
{
get
{
int i = Array.IndexOf(this.phoneNumbers,number);
if (i != -1)
{ return this.names[i]; }
else
return new Name();
}
}
public PhoneNumber this[Name name]
{
get
{
int i = Array.IndexOf(this.names,name);
if (i != 0) return this.phoneNumbers[i];
else return new PhoneNumber();
}
}
// write 1st indexer here
// write 2nd indexer here
private void enlargeIfFull()
{
if (this.used == this.names.Length)
{
int bigger = used + 16;
Name[] moreNames = new Name[bigger];
this.names.CopyTo(moreNames, 0);
PhoneNumber[] morePhoneNumbers = new PhoneNumber[bigger];
this.phoneNumbers.CopyTo(morePhoneNumbers, 0);
this.names = moreNames;
this.phoneNumbers = morePhoneNumbers;
}
}
private int used;
private Name[] names;
private PhoneNumber[] phoneNumbers;
}
}