索引器

索引器与属性的不同点:

  1、每个属性的名称必须唯一,而每一个索引器的签名必须唯一。

  2、索引器的“属性名”统一为this。而不能为其他,专门用于定义索引器。

  3、索引器的参数列表包含在方括号而不是圆括号之内。

  4、属性可以是静态的,而索引器只能为实例成员。

  5、属性的get访问器没有参数,而索引器的get访问器可以有参数,而且索引器的get访问器和set访问器的参数相同

  6、索引器可以有多个形参,比如访问多维数组时。

索引器和数组对比:

              数组          索引器

  索引类型        整型,0-n        可以为任意类型

  是否存储数据      是           否,通过访问器操作存在其他地方的数据,例如集合或数组字符串等。

  是否允许重载      否            是,一个类可以有多个索引器

标准范例:

using System;
using System.Collections.Generic;

namespace ConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            Index index = new Index();
            Console.WriteLine(index[1]);    //输出 刘备
            Console.WriteLine(index[2]);    //输出 关羽
            Console.WriteLine(index[3]);    //输出 张飞

            index[3] = "诸葛亮";
            Console.WriteLine(index[3]);    //输出 诸葛亮

            Console.ReadKey();
        }
    }

    public class Index
    {
        IDictionary<int, string> Dictionary = new Dictionary<int, string>
        {
            { 1,"刘备"},
            { 2,"关羽"},
            { 3,"张飞"},
        };
        public string this[int Id]
        {
            get
            {
                if (Dictionary.ContainsKey(Id))
                    return Dictionary[Id];
                throw new Exception("不存在对应的ID");
            }
            set
            {
                if (Dictionary.ContainsKey(Id))
                    Dictionary[Id] = value;
                else
                    throw new Exception("不存在对应的ID");
            }
        }
    }
}
View Code

 

注意:当类中有[Item]这个属性名称时 使用索引器会导致一个编译错误

错误    1    类型“ConsoleApp.BitArray”已经包含“Item”的定
解决方案:
C#允许我们通过在索引器上使用[System.Runtime.CompilerServices.IndexerName("索引名称")]这个特性来避免这种名称的冲突
但是 要注意当使用了IndexerName特性时 所有的索引器的名称 都必须一致 不然C#编译器就会报错。
using System;
using System.Collections.Generic;

namespace ConsoleApp
{
    class BitArray
    {

        private List<int> intList = new List<int>();
        public int Item { get; set; }


        [System.Runtime.CompilerServices.IndexerName("Bit")]
        public int this[int bitPos]
        {
            set
            {
                intList[bitPos] = value;
            }
            get
            {
                return intList[bitPos];
            }
        }

        //[System.Runtime.CompilerServices.IndexerName("Chars")]   如果使用的名称不一致 就会编译报错
        [System.Runtime.CompilerServices.IndexerName("Bit")]
        public int this[string str]
        {
            get { return 0; }
        }
    }


    class Program
    {
        static void Main(string[] args)
        {
            Console.ReadLine();
        }
    }
}
View Code 

转载于:https://www.cnblogs.com/scmail81/p/8605259.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值