C#的索引器

C#的索引器和属性差不多,主要是为了让类成员可以像数组一样的查询和使用,不用循环,加快了查询。但是一般的集合都实现了,比如List,Dictionary,ArrayList,数组。

在类中有个集合或数组,你有它成员的ID或关键字,就可以用索引快速的查询。


public class Person
{

    private List<Person> li = new List<Person>();  //  存储成员
    private Dictionary<string, Person> list = new Dictionary<string, Person>();  //  存储成员


    public string Name { get; set; }
    public string Height { get; set; }
    public string Weight { get; set; }

    //  数字索引
    public Person this[int index]
    {
        get
        {
            return (li[index]);
        }
        set
        {
            li.Add(value);
            list.Add(value.Name, value);
        }
    }

    // 字符索引
    public Person this[string key]
    {
        get
        {
            return this.list[key];
        }

set
        {
            this.list[value.Name] = value;
            this.li.Add(value);
        }

    }


    public override string ToString()
    {
        return "我的名字是" + Name + "  身高" + Height + " 体重" + Weight;
    }
}


在前台

// 添加成员,也可以用构造函数添加



    protected void Page_Load(object sender, EventArgs e)
    {

//  添加成员
        Person people = new Person();
        people[0] = new Person { Name = "士大夫", Height = "152", Weight = "152" };
        people[1] = new Person { Name = "他文身断发", Height = "152", Weight = "152" };
        people[2] = new Person { Name = "二手单反", Height = "152", Weight = "152" };
        people[3] = new Person { Name = "查询", Height = "152", Weight = "152" };
        people[4] = new Person { Name = "吊死扶伤啊", Height = "152", Weight = "152" };
        people[5] = new Person { Name = "玩儿", Height = "152", Weight = "152" };
        people[6] = new Person { Name = "玩儿瑞文", Height = "152", Weight = "152" };
        people[7] = new Person { Name = "额问题去", Height = "152", Weight = "152" };
        people[8] = new Person { Name = "工本费", Height = "152", Weight = "152" };
        people["qq"] = new Person { Name = "qq", Height = "152", Weight = "152" };

//  索引成员
        Response.Write(people[3].ToString());
        Response.Write(people["玩儿瑞文"].ToString());
        Response.Write(people["qq"].ToString());
        Response.Write(people[9].ToString());

这样就不必去循环匹配了

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值