using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace 索引器
{
class Program
{
static void Main(string[] args)
{
MyIndexer myindex = new MyIndexer();
myindex[0] = 23;
myindex[3] = 2;
for (int i = 0; i < myindex.Length(); i++)
{
Console.WriteLine("arr[{0}]={1}", i, myindex[i]);
}
//对象数组
MyIndexer []index1 = new MyIndexer[5];
for (int i = 0; i < index1.Length; i++)
{
index1[i] = new MyIndexer();
}
index1[1][0] = 20;
Console.WriteLine(index1[1][0]);
}
class MyIndexer
{
private int[] arr = new int[5];
public int this[int index]
{
get
{
if (index >= 0 && index <= 4) return arr[index];
else return 0;
}
set
{
if (index >= 0 && index <= 4) arr[index] = value;
}
}
public int Length()
{
return arr.Length;
}
}
}
//使用索引器访问离散字段
namespace 索引器
{
class Program
{
static void Main(string[] args)
{
PhoneBook phoneBook = new PhoneBook("张彬");
phoneBook["officephone"] = "officephone123";
phoneBook["homephone"] = "homePhone23";
phoneBook["mobilePhone"] = "mobilephone12";
phoneBook.PrintPhoneBook();
}
}
//使用索引器访问离散字段
class PhoneBook
{
private string name;
private string officePhone;
private string homePhone;
private string mobilePhone;
public PhoneBook() { }
public PhoneBook(string name)
{
this.name = name;
}
public string Name
{
get
{
return name;
}
set
{
name = value;
}
}
public string this[string type]
{
get
{
switch (type.ToLower())
{
case "officephone": return officePhone;
case "homephone": return homePhone;
case "mobilephone": return mobilePhone;
default: return null;
}
}
set
{
switch (type.ToLower())
{
case "officephone": officePhone = value; break;
case "homephone": homePhone = value; break;
case "mobilephone": mobilePhone = value; break;
default: break;
}
}
}
public void PrintPhoneBook()
{
Console.WriteLine(name);
Console.WriteLine("办公电话{0}",officePhone);
Console.WriteLine("家庭电话{0}",homePhone);
Console.WriteLine("私人电话{0}",mobilePhone);
}
}
}