C# 索引器

索引器类似属性,不过是针对数组的,索引器的使用示例如下所示:
namespace ConsoleApplication9Indexer
{
    class Class1
    {
        private string[] Strs = new string[100];


        public string this[int i]
        {
            get { return Strs[i]; }
            set { Strs[i] = value; }
        }


        private int[,] Ints = new int[10,10];


        public int this[int i,int j]
        {
            get { return Ints[i,j]; }
            set { Ints[i,j] = value; }
        }
    }


    class Program
    {
        static void Main(string[] args)
        {
            Class1 Tc = new Class1();
            Tc[1] = "sjkf";
            Console.WriteLine(Tc[1]);
            Tc[0,0] = 10;
            Console.WriteLine(Tc[0,0]);
        }
    }
}

特点:
<1>用this关键字定义索引器
<2>用get,set进行访问
<3>索引器的访问索引可以依据自定的规则,而不是必须是整数
<4>索引器可以被重载
<5>索引器可以有多个形参


推理:
<1>参数类型相同的索引器在类中只能存在一个
<2>若有多个不同索引器,必须索引器的参数不同

接口中的索引器
接口索引器不能使用访问修饰符,不能有函数体;
当类继承多个接口索引器并且索引器的参数相同的时候,需要显式的实现接口的索引器,最终索引器的使用也是只能通过接口来调用,不能通过类的对象来直接调用,示例如下:
namespace ConsoleApplication9Indexer
{
    public interface Inter1
    {
        string this[int i]
        {
            get;
            set;
        }
    }


    public interface Inter2
    {
        string this[int j]
        {
            get;
            set;
        }
    }


    public interface Inter3
    {
        string this[int i]
        {
            get;
            set;
        }
    }
    class Class2 : Inter1,Inter2,Inter3
    {
        private string[] names = new string[100];
        private string[] sexs = new string[100];
        private string[] Adds = new string[100];


        string Inter1.this[int i]
        {
            get { return names[i]; }
            set { names[i] = value; }
        }


        string Inter2.this[int j]
        {
            get { return sexs[j]; }
            set { sexs[j] = value; }
        }


        public string this[int i]
        {
            get { return Adds[i]; }
            set { Adds[i] = value; }
        }
    }


	static void Main(string[] args)
        {
            Class2 Ts = new Class2();
            Inter1 Inters1 = (Inter1)Ts;
            Inters1[11] = "whjhd";
            Console.WriteLine(Inters1[11]);
            Inter2 Inters2 = (Inter2)Ts;
            Inters2[67] = "what a fucking day";
            Console.WriteLine(Inters2[67]);
	}
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值