C#中的索引器

索引器是C#的一项特殊功能,可以将对象用作数组。如果在类中定义索引器,则其行为将类似于虚拟数组。索引器在C#中也称为智能数组。它不是OOPS的强制性或必要部分。

也称为索引属性。它是一个类属性,允许使用数组功能访问数据成员。

我们使用该对象在类中实现索引器。

语法:

<Modifier> <return type> this[parameter list]
{
	get
	{
		//在这里写代码
	}

	set
	{
		//在这里写代码
	}
}

using System;
using System.Collections;
namespace ConsoleApplication1
{
    
    class Names
    {
        static public int len=10;
        private string []names = new string[len]    ;


        public Names()
        {
            for (int loop = 0; loop < len; loop++)
                names[loop] = "N/A";
        }
        public string this[int ind]
        {
            get
            {
                string str;
                if (ind >= 0 && ind <= len - 1)
                    str = names[ind];
                else
                    str = "...";
                return str;
            }

            set
            {
                if (ind >= 0 && ind <= len - 1)
                    names[ind]=value;
            }
        }
    }

    class Program
    {
        static void Main()
        {
            Names names = new Names();

            names[0] = "Duggu";
            names[1] = "Shaurya";
            names[2] = "Akshit";
            names[3] = "Shivika";
            names[4] = "Veer";

            for (int loop = 0; loop < Names.len; loop++)
            {
                Console.WriteLine(names[loop]);
            }

        }
    }
}

输出结果

    Duggu
    Shaurya
    Akshit
    Shivika
    Veer
    N/A
    N/A
    N/A
    N/A
    N/A

关于索引器的要点:

  • 我们使用此关键字来实现索引器。

  • 索引器可能过载。

  • 索引器不能是静态的。

阅读更多: C#中的索引器重载