.net中的索引器

来源:互联网 发布:android判断网络类型 编辑:程序博客网 时间:2024/05/17 21:27

.net中的索引器主要是针对集合的属性,让使用者更加方便的使用集合成员。

下面先定义一个Person的类,然后为该类创建一个索引器。

 class Person    {        private string FirstName = "phone";        private string SecondName = "ball";        //为类创建索引器,格式为:访问修饰符+类型+this[参数1,参数2,.....]        public  string this[int index]        {            set            {                if (index == 1)                {                    FirstName = value;                }                else if (index == 2)                {                    SecondName = value;                }                else                {                    throw new Exception("错误的序号!");                }            }            get            {                if (index == 1)                {                    return FirstName;                }                else if (index == 2)                {                    return SecondName;                }                else                {                    throw new Exception("错误的序列号!");                }            }        }
索引器看上去和属性很像,但是他们是有区别的:

1、定义方式是不同的,索引器必须用this[]这种格式,属性只需要对字段进行get;set;封装就好了

2、索引器是索引参数列表,而属性没有参数

0 0
原创粉丝点击