关于C#索引器的基本用法
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
namespace 索引器
{
class Program
{
static void Main(string[] args)
{
B b = new B();
A a = new A();
a[0] = "李四";
a[1] ="王五";
Console.WriteLine("a0是" + a[0] );
Console.WriteLine("a1是" + a[1] );
b[0] = "李四";
b[1] = "王五";
b[2] = "马六";
Console.WriteLine("b0是" + b[0]);
Console.WriteLine("b1是" + b[1]);
Console.WriteLine("李四是" + b["李四"] + "号");
Console.WriteLine("王五是" + b["王五"] + "号");
Console.ReadLine();
}
}
class A
{
public ArrayList list = new ArrayList();
public string this[int id]
{
get
{
foreach(C a in list)
{
if(a.Id==id)
{
return a.Name;
}
}
return null;
}
set
{
list.Add(new C(value,id));
}
}
}
class C
{
private string m_Name;
private int m_Id;
public string Name
{
get
{
return m_Name;
}
set
{
m_Name = value;
}
}
public int Id
{
get
{
return m_Id;
}
set
{
m_Id = value;
}
}
public C(string n, int i)
{
this.m_Name = n;
this.m_Id = i;
}
}
class B
{
private Hashtable people = new Hashtable();
//根据名字找ID
public int this[string nm]
{
get
{
foreach (DictionaryEntry p in people)
{
if (p.Value.ToString() == nm)
{
return int.Parse(p.Key.ToString());
}
}
return -1;
}
set
{
people.Add(value, nm);
}
}
//根据ID找名字
public string this[int id]
{
get
{
return people[id].ToString();
}
set
{
people.Add(id, value);
}
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
namespace 索引器2
{
class Program
{
static void Main(string[] args)
{
B b = new B();
b[1, "李四"] = 39;
b[2, "王五"] = 40;
Console.WriteLine("今年李四" + b[1, "李四"]+"岁");
Console.WriteLine("今年王五" + b[2, "王五"] + "岁");
Console.ReadLine();
}
}
class A
{
private int m_Id;
public int Id
{
get { return m_Id; }
set { m_Id = value; }
}
private string m_Name;
public string Name
{
get { return m_Name; }
set { m_Name = value; }
}
private int m_Age;
public int Age
{
get { return m_Age; }
set { m_Age = value; }
}
public A(int id, string name, int age)
{
this.m_Id = id;
this.m_Name = name;
this.m_Age = age;
}
}
class B
{
ArrayList list = new ArrayList();
public int this[int id, string name]
{
get
{
foreach (A a in list)
{
if(a.Id==id&&a.Name==name)
{
return a.Age;
}
}
return -1;
}
set
{
list.Add(new A(id, name, value));
}
}
}
}