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

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();
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值