您的位置:首页 > 编程语言 > C#

c#基础知识学习笔记 - 索引器

2013-05-05 14:14 615 查看
using System;
//带索引器的类
class IndexClass
{
private string[] name = new string[10];
public string this[int index]
{
get { return name[index]; }
set { name[index] = value; }
}
}
class Test
{
static void Main()
{
//索引器的使用
IndexClass b = new IndexClass();
b[0] = "张三";
b[1] = "李四";
b[2] = "王五";
for (int i = 0; i < 3; i++)
{
Console.WriteLine("a[{0}] = {1}", i, b[i]);
}
Console.Read();
}
}


using System;
using System.Collections;
//带索引器的类
class IndexClass
{
private Hashtable name = new Hashtable();
public string this[string index]
{
get { return name[index].ToString(); }
set { name.Add(index, value); }
}
}
class Test
{
static void Main()
{
//索引器的使用
IndexClass b = new IndexClass();
b["A001"] = "张三";
b["A002"] = "李四";
b["A003"] = "王五";
Console.WriteLine("b[A001] = " + b["A001"]);
Console.WriteLine("b[A002] = " + b["A002"]);
Console.WriteLine("b[A003] = " + b["A003"]);
Console.Read();
}
}


using System;
using System.Collections;
//带索引器的类
class IndexClass
{
private Hashtable name = new Hashtable();
public string this[int index]
{
get { return name[index].ToString(); }
set { name.Add(index, value); }
}
public int this[string aname]
{
get
{
foreach (DictionaryEntry d in name)
{
if (d.Value.ToString() == aname)
return Convert.ToInt32(d.Key);
}
return -1;
}
set
{
name.Add(value, aname);
}
}
}
class Test
{
static void Main()
{
//索引器的使用
IndexClass b = new IndexClass();
b[100] = "张三";
b[200] = "李四";
b[300] = "王五";
Console.WriteLine("编号为100的员工是:" + b[100]);
Console.WriteLine("编号为200的员工是:" + b[200]);
Console.WriteLine("编号为300的员工是:" + b[300]);
Console.WriteLine("张三的编号是:" + b["张三"]);
Console.WriteLine("李四的编号是:" + b["李四"]);
Console.WriteLine("王五的编号是:" + b["王五"]);
b["马六"] = 400;
b["钱七"] = 500;
Console.WriteLine("马六的编号是:" + b["马六"]);
Console.WriteLine("钱七的编号是:" + b["钱七"]);
Console.Read();
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: